sql學習~pivot和unpivot用法


pivot 

可以把列值轉換為輸出中的多個列。

pivot 可以在其他剩余的列的值上執行聚合函數。

unpivot

將列轉換為列值

語法

SELECT <non-pivoted column>,  
    [first pivoted column] AS <column name>,  
    [second pivoted column] AS <column name>,  
    ...  
    [last pivoted column] AS <column name>  
FROM  
    (<SELECT query that produces the data>)   
    AS <alias for the source query>  
PIVOT  
(  
    <aggregation function>(<column being aggregated>)  
FOR   
[<column that contains the values that will become column headers>]   
    IN ( [first pivoted column], [second pivoted column],  
    ... [last pivoted column])  
) AS <alias for the pivot table>  
<optional ORDER BY clause>;

 

示例1:pivot

1.數據准備

create table student_score
(
    studentId varchar(50),
    subjectName varchar(50),
    score decimal(18)
)

insert into student_score values
('001','語文',80),('001','數學',70),('001','英語',90),
('002','語文',80),('002','數學',83),('002','英語',60),
('003','語文',50),('003','數學',90),('003','英語',60),
('004','語文',90),('004','數學',80)

按學生id分組查看平均成績

select studentId,AVG(score) avgScore from student_score
group by studentId

初始效果

 

 2.使用pivot

select 'averagescore' as avgScore_by_studentId,
[001],[002],[003],[004]
from 
(
select studentId,score 
    from student_score
) as sourceTable
pivot
(
AVG(score) for studentId in ([001],[002],[003],[004])
) as pivotTable

3.效果

 

示例2:unpivot 

1.數據准備

-- Create the table and insert values as portrayed in the previous example.  
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,  
    Emp3 int, Emp4 int, Emp5 int);  
GO  
INSERT INTO pvt VALUES (1,4,3,5,4,4);  
INSERT INTO pvt VALUES (2,4,1,5,5,5);  
INSERT INTO pvt VALUES (3,4,3,5,4,4);  
INSERT INTO pvt VALUES (4,4,2,5,5,4);  
INSERT INTO pvt VALUES (5,5,1,5,5,5);  
GO 

初始效果

 

 表示供應商(vendorID)在用戶1(Emp1)中的訂單數量,其他類比即可。

2.使用示例

-- Unpivot the table.  
SELECT VendorID, Employee, Orders  
FROM   
   (SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5  
   FROM pvt) p  
UNPIVOT  
   (Orders FOR Employee IN   
      (Emp1, Emp2, Emp3, Emp4, Emp5)  
)AS unpvt;  

3.效果

 

 

參考網址


免責聲明!

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



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