gpt4 book ai didi

sql - Postgres - 也许是交叉表?

转载 作者:行者123 更新时间:2023-11-29 11:43:32 25 4
gpt4 key购买 nike

我有一个包含 3 列的表 A-

date       | type | value
_________________________
2012-01-01 | 1 | 100
2012-01-01 | 2 | 200

2012-01-02 | 1 | 200
2012-01-02 | 2 | 300

2012-01-03 | 1 | 500
2012-01-03 | 2 | 10

对于这种格式的数据,是否有可能获得查询结果-

date       |     type-1     |  type-2
_____________________________________
2012-01-01 100 200
2012-01-02 200 300

这看起来像是一个交叉表问题。虽然不确定。有什么想法可以为此编写 SQL 吗?

最佳答案

您可以使用带有 CASE 表达式的聚合函数来获取结果:

select date,
sum(case when type = 1 then value end) Type1,
sum(case when type = 2 then value end) Type2
from yourtable
group by date

参见 SQL Fiddle with Demo

您还可以多次加入同 table :

select t1.date,
t1.value Type1,
t2.value Type2
from yourtable t1
left join yourtable t2
on t1.date = t2.date
and t2.type = 2
where t1.type = 1

参见 SQL Fiddle with Demo

关于sql - Postgres - 也许是交叉表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14863985/

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