SQL Server行列转换隐藏group
Pivot有一个隐藏的Group 分组, 除了Pivot column 和value列,其他列作为分组
Example:
IF NOT EXISTS(SELECT * FROM sys.tables where name = ‘Pivot_test‘)
CREATE TABLE Pivot_test
(
id1 int,
id2 int,
Pivot_column varchar(50),
value char(50)
)
insert into Pivot_test values(1,1,‘A‘,‘A_V‘),(1,1,‘B‘,‘B_V‘),(1,1,‘C‘,‘C_V‘),(1,1,‘D‘,‘D_V‘)
行列转换
select * from Pivot_test PIVOT(MAX(value) for Pivot_column in (A,B,C,D)) tem
更新A的id2值为2,再次行列转换,发现出现两行,证明id2影响了分组
update Pivot_test set id2 = 2 WHERE Pivot_column = ‘A‘
select * from Pivot_test PIVOT(MAX(value) for Pivot_column in (A,B,C,D)) tem
更新A的id1值为2,id2更新为旧的值1,再次查看行列转换结果,发现结果仍为两行,证明id1也在分组中
update Pivot_test set id2 = 1 WHERE Pivot_column = ‘A‘
update Pivot_test set id1 = 2 WHERE Pivot_column = ‘A‘
select * from Pivot_test PIVOT(MAX(value) for Pivot_column in (A,B,C,D)) tem
以上证明pivot是以除了Pivot column 和value的其他所有列作为分组
原文:http://www.cnblogs.com/qianlixing/p/6648622.html