SQL SERVER中PIVOT和UNPIVOT

SQL SERVER中PIVOT和UNPIVOT



PIVOT和UNPIVOT



PIVOT 通過將表達式某一列中的唯一值轉換爲輸出中的多個列來旋轉表值表達式,並在必要時對最終輸出中所需的任何其餘列值執行聚合。UNPIVOT 與 PIVOT 執行相反的操作,將表值表達式的列轉換爲列值。


基本準備:


create table TestPivot
(
    name varchar(50)
)
insert into testpivot(name)
select 'DePaul'
union all
select 'DePaul'
union all
select 'LeeWhoeeUniversity'
union all
select 'LeeWhoeeUniversity'
union all
select 'LeeWhoee'
union all
select 'LeeWhoee'
union all
select 'LeeWhoee'




用下面的查詢當做一個表來操作
select name,count(*) as totalcount from testpivot
group by name

運行結果:

name                         totalcount
LeeWhoee                       3
DePaul                             2

LeeWhoeeUniversity        2


上面是我們將要操作的表數據


PIVOT


select 'totalcount' as name,[LeeWhoee],[DePaul],[LeeWhoeeUniversity]
    from
    (
    select name,count(*) as totalcount from testpivot
    group by name
    ) a
    pivot
    (
        max(totalcount) for name in ([LeeWhoee],[LeeWhoeeUniversity],[DePaul])
    ) b


運行結果:


name             LeeWhoee    DePaul    LeeWhoeeUniversity
totalcount      3                         2                  2


UNPIVOT


下面使用UNPIVOT將此結果集反轉成初始結果集


select _name as name,_totalcount as totalcount
from 
(
    select 'totalcount' as name,[LeeWhoee],[DePaul],[LeeWhoeeUniversity]
    from
    (
    select name,count(*) as totalcount from testpivot
    group by name
    ) a
    pivot
    (
        max(totalcount) for name in ([LeeWhoee],[LeeWhoeeUniversity],[DePaul])
    ) b
) d
unpivot
(
     _totalcount for _name  in([LeeWhoee],[DePaul],[LeeWhoeeUniversity])
) c



運行結果:


name                         totalcount
LeeWhoee                      3 
DePaul                            2

LeeWhoeeUniversity      2



發佈了87 篇原創文章 · 獲贊 292 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章