--ProductID OrderMonth SubTotal 
--1 5 100.00 
--1 6 100.00 
--2 5 200.00 
--2 6 200.00 
--2 7 300.00 
--3 5 400.00 
--3 5 400.00 
--
set nocount on

create table T1(ProductID int ,OrderMonth int,SubTotal int)
insert into T1 select 1,5,100
union all select 1,6,100
union all select 2,5,200
union all select 2,6,200
union all select 2,7,300
union all select 3,5,400
union all select 3,5,400

select * from T1

select ProductID ,[5] [五月],[6] [六月],[7] [七月] from T1
pivot
(sum(SubTotal)
for OrderMonth in ([5],[6],[7])) as p
drop table T1


----returns
ProductID OrderMonth SubTotal
----------- ----------- -----------
1 5 100
1 6 100
2 5 200
2 6 200
2 7 300
3 5 400
3 5 400

ProductID 五月 六月 七月
----------- ----------- ----------- -----------
1 1 1 0
2 1 1 1
3 2 0 0

本文通过一个具体的 SQL 查询案例,展示了如何使用 Pivot 操作来转换表格数据的结构,从而实现从行到列的数据透视效果。该过程包括创建临时表、插入数据、应用 Pivot 函数以及最终删除临时表。
4909

被折叠的 条评论
为什么被折叠?



