pivot 和unpivot用法一目了然


if  object_id( ' tb ') is  not  null 
drop  table tb
go

create  table tb(
    Name  varchar( 10),
    Course  varchar( 10),
    Score  int
)
go

insert     into tb  values( ' 張三 ', ' 語文 ', 74)
insert     into tb  values( ' 張三 ', ' 數學 ', 83)
insert     into tb  values( ' 張三 ', ' 物理 ', 93)
insert     into tb  values( ' 李四 ', ' 語文 ', 74)
insert     into tb  values( ' 李四 ', ' 數學 ', 84)
insert     into tb  values( ' 李四 ', ' 物理 ', 94)
go

select  *  from tb
go

-- Old Way
select 
    Name, 
     MAXcase Course  when  ' 語文 '  then Score  else  0  endas 語文,
     MAXcase Course  when  ' 數學 '  then Score  else  0  endas 數學,
     MAXcase Course  when  ' 物理 '  then Score  else  0  endas 物理    
from tb
group  by Name

go

-- PIVOT
select  *  from tb 
pivot(
     max(Score)  for Course  in( [ 語文 ], [ 數學 ], [ 物理 ])
    ) pivotedTb 
order  by Name
go

-- UNPIVOT
select  *  from 
(
     select  *  from tb 
    pivot(
         max(Score)  for Course  in( [ 語文 ], [ 數學 ], [ 物理 ])
    ) pivotedTb 
    
) sourceTb

unpivot(
    Score  for Course  in( [ 語文 ], [ 數學 ], [ 物理 ])
) unPivotedTb

簡單演示了一下SQL Server2005 中的一對很有用的操作:PIVOT ,UNPIVOT

代碼如下: 

 

 

if  object_id( ' tb ') is  not  null 
drop  table tb
go

create  table tb(
    Name  varchar( 10),
    Course  varchar( 10),
    Score  int
)
go

insert     into tb  values( ' 張三 ', ' 語文 ', 74)
insert     into tb  values( ' 張三 ', ' 數學 ', 83)
insert     into tb  values( ' 張三 ', ' 物理 ', 93)
insert     into tb  values( ' 李四 ', ' 語文 ', 74)
insert     into tb  values( ' 李四 ', ' 數學 ', 84)
insert     into tb  values( ' 李四 ', ' 物理 ', 94)
go

select  *  from tb
go

--Old Wayselect 
    Name, 
    MAXcase Course when '語文' then Score else 0 endas 語文,
    MAXcase Course when '數學' then Score else 0 endas 數學,
    MAXcase Course when '物理' then Score else 0 endas 物理    
from tb
group by Name

go

--PIVOT
select * from tb 
pivot(
    max(Score) for Course in([語文],[數學],[物理])
    ) pivotedTb 

order by Name
go

--UNPIVOT
select * from 
(
    select * from tb 
    pivot(
        max(Score) for Course in([語文],[數學],[物理])
    ) pivotedTb 
    
sourceTb

unpivot(
    Score for Course in([語文],[數學],[物理])
) unPivotedTb

go 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM