반응형

/********************************************************************************************
-- Title : [2012] Pivot, Unpivot, Cross Join, Case문을 활용한 변환
-- Reference : dbrang.tistory.com
-- Key word : pivot unpivot 피벗 언피벗 피벗팅 cross join
********************************************************************************************/

use tempdb;
go

/*

-- PIVOT & CASE
-- 행을 열로(ㄴ)
-- 1:다 테이블을 1:1로 변환


*/

drop table ttt;

create table ttt
( region nvarchar(5)
, cnt int
);

insert into ttt
select '서울', 111 union all
select '대전', 222 union all
select '대구', 333 union all
select '부산', 444 union all
select '광주', 555;

select * from ttt;


-- PIVOT 연산자 이용
-- 대괄호[]를 꼭! 사용해야 하더이다.
with www as
(
select 1 "rset", region, cnt
from ttt
)
select rset, [서울] "서울", [대전] "대전", [대구] "대구", [부산] "부산", [광주] "광주"
from www
pivot
( sum(cnt) for region in ( [서울], [대전], [대구], [부산], [광주])
) as pvt;

-- CASE 이용
with www as
(
select 1 "rset", region, cnt
from ttt
)
select rset, max(case when region = '서울' then cnt else null end) "서울"
           , max(case when region = '대전' then cnt else null end) "대전"
           , max(case when region = '대구' then cnt else null end) "대구"
           , max(case when region = '부산' then cnt else null end) "부산"
           , max(case when region = '광주' then cnt else null end) "광주"
from www
group by rset;


/*

-- UNPIVOT & CROSS JOIN
-- 열을 행으로(ㄱ)
-- 1:1을 1:다로 변환


*/

drop table ttt;

create table ttt
( rset int
, 서울 int
, 대전 int
, 대구 int
, 부산 int
, 광주 int
);

insert into ttt
select 1, 111,222,333,444,555;

select * from ttt;

-- UNPIVOT 연산자 이용
select rset, region, cnt
from
(
    select rset, 서울, 대전, 대구, 부산, 광주
    from ttt
) p
unpivot
( cnt for region in (서울, 대전, 대구, 부산, 광주)
) upvt;

-- CROSS JOIN 이용
with www as
(
    select row_number() over (order by case when b.region = '서울' then 1
                                            when b.region = '대전' then 2
                                            when b.region = '대구' then 3
                                            when b.region = '부산' then 4
                                            when b.region = '광주' then 5
                                       end
                             ) "rnum", *
    from ttt a
    cross join
    (
        select '서울' "region" union all
        select '대전' union all
        select '대구' union all
        select '부산' union all
        select '광주'
    ) b
)
select rnum
     , region
     , case when rnum = 1 then 서울
            when rnum = 2 then 대전
            when rnum = 3 then 대구
            when rnum = 4 then 부산
            when rnum = 5 then 광주
       end "cnt"
from www;


 

 

 

반응형

+ Recent posts