2014-03-03 75 views
1

我不知道是否有可能作出这样的查询。问题是我有一张桌子,那里有一些数字。 可以说我有3列:日期,金额,好/坏Postgres的复杂查询

即:

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

我想选择和减去好 - 坏:

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

这可能吗?我想了很多,并没有一个想法。如果我在单独的表中有好的和坏的值,这将是相当简单的。

+0

你有确切2行1.良好的&2.坏,对于每一日期? – 2014-03-03 11:44:11

回答

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 

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

+0

注:第一个解决方案将失败天的*仅*“好”或*只*“坏”的看法存在。 – joop

+0

我终于测试了你的答案。当1点的方法将失效的情况不应该在我的情况发生,我用它给了你第二个前:)它的工作原理究竟是怎么想的工作。非常感谢你:) –