2014년 4월 11일 금요일

MS-SQL 에서 가로 출력법


원문 : http://database.sarang.net/?inc=read&aid=4438&criteria=mssql&subcrit=&id=&limit=20&keyword=%B1%DD%BE%D7&page=1

오라클에서 가로로 결과물을 출력시 decode 를 사용하지만, Ms-Sql 에서는 case 를 사용해 가로로 출력할 수 있다.


(테이블)
상환일자    원금   이자  잔액
 ---------------------------
 2008-05-25 10000 1000 121000
 2008-06-25 10000 1000 110000
 2008-07-25 10000 1000 99000
 2008-08-25 10000 1000 88000
 2008-09-25 10000 1000 77000
 2008-10-25 10000 1000 66000
 2008-11-25 10000 1000 55000
 2008-12-25 10000 1000 44000
 2009-01-25 10000 1000 33000
 2009-02-25 10000 1000 22000
 2009-03-25 10000 1000 11000
 2009-04-25 10000 1000 0

(출력)
연도 구분 1월   2월    3월   4월    5월    6월   7월   8월   9월   10월  11월  12월
 ---------------------------------------------------------------------------------------------------
 2008 원금  null  null  null  null  10000  10000 10000 10000 10000 10000 10000 10000
 2008 이자  null  null  null  null   1000   1000  1000  1000  1000  1000  1000  1000
 2008 잔액  null  null  null  null 121000 110000 99000 88000 77000 66000 55000 44000
 2009 원금 10000 10000 10000 10000   null   null  null  null  null  null  null  null
 2009 이자  1000  1000  1000  1000   null   null  null  null  null  null  null  null
 2009 잔액 33000 22000 11000     0   null   null  null  null  null  null  null  null

(쿼리)
select
       year(상환일자) 연도,
       구분,
       sum(case datepart(mm,상환일자) when 1 then 금액 end) [1월],
       sum(case datepart(mm,상환일자) when 2 then 금액 end) [2월],
       sum(case datepart(mm,상환일자) when 3 then 금액 end) [3월],
       sum(case datepart(mm,상환일자) when 4 then 금액 end) [4월],
       sum(case datepart(mm,상환일자) when 5 then 금액 end) [5월],
       sum(case datepart(mm,상환일자) when 6 then 금액 end) [6월],
       sum(case datepart(mm,상환일자) when 7 then 금액 end) [7월],
       sum(case datepart(mm,상환일자) when 8 then 금액 end) [8월],
       sum(case datepart(mm,상환일자) when 9 then 금액 end) [9월],
       sum(case datepart(mm,상환일자) when 10 then 금액 end) [10월],
       sum(case datepart(mm,상환일자) when 11 then 금액 end) [11월],
       sum(case datepart(mm,상환일자) when 12 then 금액 end) [12월]
 from (
         select
              a.상환일자,
              b.구분,
              case b.구분 when '원금' then a.원금 
                          when '이자' then a.이자 
                          when '잔액' then a.잔액 
              end 금액
         from
              test a
             ,(select '원금' 구분 union all select '이자' union all select '잔액') b
      ) t
group by year(상환일자),구분
order by year(상환일자),구분