연월, 상품, 수량을 가지고 연월별 통계를 쿼리로 짤수 있을까요? 0 1 1,215

by 깨복숭이 [SQL Query] [2022.08.12 14:47:16]


상품코드 CNT
202201 20 15
202205 20 2
202206 20 1
202202 22 82
202207 22 21
202210 22 8
202209 M4 248
202208 M6 1
202209 N3 275

위의 데이터를 가지고 아래의 통계 데이터를 만들 수 있을까요 

  202201 202202 202203 202204 202205 202206 202207 202208 202209 202210
20 15       2 1        
22   82         21     8
M4                 248  
M6               1    
N3                 275  

 

by pajama [2022.08.12 16:03:27]

오라클이나 pivot 지원되는 dbms 사용하시면 pivot으로 가능합니다.

pivot 사용법이 잘 안외워져서 찾아서 해봤습니다...

 

with t (mon, cod, cnt) as (
select '202201' , '20', 15 from dual union all
select '202205' , '20', 2 from dual union all
select '202206' , '20', 1 from dual union all
select '202202' , '22', 82 from dual union all
select '202207' , '22', 21 from dual union all
select '202210' , '22', 8 from dual union all
select '202209' , 'M4', 248 from dual union all
select '202208' , 'M6', 1 from dual union all
select '202209' , 'N3', 275 from dual
)
select * from t
pivot ( min(cnt) for mon in
         ('202201', '202202', '202203', '202204', '202205', '202206', '202207', '202208', '202209', '202210'))
;

pivot이 안되면 아래 방식으로 가능할듯 합니다.


select cod, 
        min(case when mon ='202201' then cnt end) as "202201",
        min(case when mon ='202202' then cnt end) as "202202",
        ...
from t
group by cod
order by cod

 

댓글등록
SQL문을 포맷에 맞게(깔끔하게) 등록하려면 code() 버튼을 클릭하여 작성 하시면 됩니다.
로그인 사용자만 댓글을 작성 할 수 있습니다. 로그인, 회원가입