SqlServer的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.效果
分类:
SqlServer
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!