2014-04-04 99 views
0

我有一個要求來計算基於同一列上不同條件的記錄數。下面是例子。請讓我知道如何做到這一點。替代在oracle中的關鍵點

表中有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 

回答

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;