關鍵是要加入你的表回到它自身,如下圖所示。 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
兩種方法產生相同的結果。
你有確切2行1.良好的&2.壞,對於每一日期? – 2014-03-03 11:44:11