postgres复杂的查询

时间:2014-03-03 10:59:16

标签: postgresql select subtraction

我想知道是否可以进行此类查询。问题是我有一张桌子,其中有一些数字用于约会。 假设我有3列:日期,价值,好/坏

即:

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

有可能吗?我在想很多,但还没有想法。如果我在单独的表中有好的和坏的值,那将会相当简单。

1 个答案:

答案 0 :(得分:1)

诀窍是将你的桌子自己加入,如下图所示。 myTable as A只会读取Good行,而myTable as B只会读取Bad行。然后,这些行将基于date加入到一个符号行中。

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

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

相关问题