我需要根据同一列上的不同条件计算记录数。以下是示例。请告诉我如何实现这一目标。
表有4列,分别为C1,C2,C3,no_of_days和数据,如下所示。
C1|C2|C3|no_of_days
--------------------
A |B |C |7
X |B |C |8
Z |D |E |15
Y |D |E |22
P |D |E |34
Q |R |S |8
我需要以下面的格式显示数据
C2|C3|<=7D|8-14D|15-21D|22-27D
------------------------------
B |C |1 |1 |0 |0
D |E |0 |1 |1 |1
R |S |0 |1 |0 |0
答案 0 :(得分:3)
您按C2和C3进行分组并总结事件:
select c2, c3
, sum( case when no_of_days <= 7 then 1 else 0 end) as dlt8
, sum( case when no_of_days between 8 and 14 then 1 else 0 end) as d8to14
, sum( case when no_of_days between 15 and 21 then 1 else 0 end) as d15to21
, sum( case when no_of_days between 22 and 27 then 1 else 0 end) as d22to27
from mytable
group by c2, c3
order by c2, c3;