안녕하세요
name | date
A | 1월
A | 2월
B | 1월
B | 2월
B | 2월
B | 4월
C | 5월
...
월별 통계를 내려고 하는데요
이런 형식에서 pivot을 만들면
A B C D
1월 1 1 0 0
2월 1 2 0 0
4월 0 0 0 0
5월 0 0 1 0
이렇게 3월이 빠지게 되는데 해당 월에 데이터가 없어도 1월부터12까지 모두 세로로 표시가 되게 하려면 어떤 방법이 좋을까요
월을 가로로 표기할려고 하면 D라는 항목이 데이터가 하나도 없어서 표기가 안되서 똑같은 고민입니다..
참고하세요
with tbl as (
select 'A' nm, '01월' dt union all
select 'A' nm, '02월' dt union all
select 'B' nm, '01월' dt union all
select 'B' nm, '02월' dt union all
select 'B' nm, '02월' dt union all
select 'B' nm, '04월' dt union all
select 'C' nm, '05월' dt
),
mon as (
select '01월' dt union all
select '02월' dt union all
select '03월' dt union all
select '04월' dt union all
select '05월' dt union all
select '06월' dt union all
select '07월' dt union all
select '08월' dt union all
select '09월' dt union all
select '10월' dt union all
select '11월' dt union all
select '12월' dt
)
select mon.dt
, count(case when nm = 'A' then 1 end) nm_A
, count(case when nm = 'B' then 1 end) nm_B
, count(case when nm = 'C' then 1 end) nm_C
, count(case when nm = 'D' then 1 end) nm_D
from mon
left outer join tbl
on tbl.dt = mon.dt
group by mon.dt