gpt4 book ai didi

sql根据where子句查询列名

转载 作者:行者123 更新时间:2023-11-29 11:44:40 24 4
gpt4 key购买 nike

我正在尝试从 1 个表运行 sql 查询,我希望每个结果列中的数据基于不同的 where 子句。

例子:

我有一个名为 messages 的表,其中包含名为 type、size、country 的列

type 的值包括电子邮件和短信。

大小的值为整数。

我想创建一个包含 3 列的 View :国家、短信、电子邮件。然后,我想显示每个国家/地区的电子邮件和短信的大小总和。

我想我需要一个用于列标题的 where 子句,但我不知道该怎么做。

我正在尝试做类似的事情:

select country, sum(size) 
where type = 'sms' as "SMS", sum(size)
where type = 'email' as "Email"
from messages table
group by country

我希望我试图完成的事情的逻辑是清楚的。我无法弄清楚语法。有人可以帮忙吗?谢谢!

注意:db为postgressql。

最佳答案

您可以像这样对 case 表达式使用条件聚合:

select 
country
, sum(case when type='email' then size else 0 end) as email
, sum(case when type='sms' then size else 0 end) as sms
from messages
group by country

关于sql根据where子句查询列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44004482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com