PIVOT用于将行转为列,完整语法如下:

TABLE_SOURCE

PIVOT(

聚合函数(value_column)

FOR pivot_column

IN(<column_list>)
)

UNPIVOT用于将列转为行,完整语法如下:
完整语法:
TABLE_SOURCE

UNPIVOT(

value_column

FOR pivot_column

IN(<column_list>)
)

以上语法可以理解为value_column字段与pivot_column字段的行列(列行)转换,pivot_column字段显示的列/行为column_list

--建张表Table_A

create table Table_A(name varchar(8),Math int,English int,Chinese int)
insert into Table_A values('小A',80,90,88)
insert into Table_A values('小B',70,90,85)
insert into Table_A values('小C',75,95,85)
insert into Table_A values('小D',80,90,75)

--原始表数据

select * from Table_A

nameMathEnglishChinese
小A809088
小B709085
小C759585
小D809075

--UNPIVOT用于将列转为行

select Subject,name,Grade from Table_A
unpivot(Grade for Subject in ([Math],[English],[Chinese])) as s

SubjectnameGrade
Math小A80
English小A90
Chinese小A88
Math小B70
English小B90
Chinese小B85
Math小C75
English小C95
Chinese小C85
Math小D80
English小D90
Chinese小D75

--PIVOT函数用于将行转为列

select * from
(
    select Subject,name,Grade from Table_A
    unpivot(Grade for Subject in ([Math],[English],[Chinese])) as s
) as a
pivot(sum(Grade) for name in ([小A],[小B],[小C],[小D])) as b

Subject小A小B小C小D
Chinese88858575
English90909590
Math80707580

实现多行多列转换,请参考:http://www.cnblogs.com/hbwy/p/4359209.html

05-11 21:54