gpt4 book ai didi

postgresql - postgres复杂查询

转载 作者:行者123 更新时间:2023-11-29 13:31:29 26 4
gpt4 key购买 nike

我不知道是否可以进行这样的查询。问题是我有一张表,其中有一些日期数字。假设我有 3 列:日期、值(value)、好/坏

即:

2014-03-03 100 Good
2014-03-03 15 Bad
2014-03-04 120 Good
2014-03-04 10 Bad

我想选择并减去 Good-Bad:

2014-03-03 85
2014-03-04 110

这可能吗?我想了很多,还没有主意。如果我在单独的表中有 Good 和 Bad 值,那将相当简单。

最佳答案

诀窍是将您的表重新连接到它自己,如下所示。 myTable as A 将只读取Good 行,myTable as B 将只读取Bad 行。然后根据日期将这些行连接成一个单行。

SQL Fiddle Demo

select 
a.date
,a.count as Good_count
,b.count as bad_count
,a.count-b.count as diff_count
from myTable as a
inner join myTable as b
on a.date = b.date and b.type = 'Bad'
where a.type = 'Good'

返回的输出:

DATE                            GOOD_COUNT  BAD_COUNT   DIFF_COUNT
March, 03 2014 00:00:00+0000 100 15 85
March, 04 2014 00:00:00+0000 120 10 110

另一种方法是使用 Group by 而不是 inner join:

select 
a.date
,sum(case when type = 'Good' then a.count else 0 end) as Good_count
,sum(case when type = 'Bad' then a.count else 0 end) as Bad_count
,sum(case when type = 'Good' then a.count else 0 end) -
sum(case when type = 'Bad' then a.count else 0 end) as Diff_count
from myTable as a
group by a.date
order by a.date

两种方法产生相同的结果。

关于postgresql - postgres复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22144958/

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