2014-03-03 99 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點的方法將失效的情況不應該在我的情況發生,我用它給了你第二個前:)它的工作原理究竟是怎麼想的工作。非常感謝你:) –