문제

I have a requirement to count the number of records based on different conditions on the same column. Below is the example. Please let me know how to achieve this.

Table have 4 columns say C1, C2, C3, no_of_days and data as below.

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

I need to display the data in the format like below

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
도움이 되었습니까?

해결책

You group by C2 and C3 and sum up the occurrences:

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top