关键是要加入你的表回到它自身,如下图所示。 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