PIVOT函数与UNPIVOT函数的运用
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
name | Math | English | Chinese |
小A | 80 | 90 | 88 |
小B | 70 | 90 | 85 |
小C | 75 | 95 | 85 |
小D | 80 | 90 | 75 |
--UNPIVOT用于将列转为行
select Subject,name,Grade from Table_A
unpivot(Grade for Subject in ([Math],[English],[Chinese])) as s
--如果上面不能执行,用下面这个
select Subject,name,Grade from Table_A
unpivot(Grade for Subject in (Math,English,Chinese))
Subject | name | Grade |
Math | 小A | 80 |
English | 小A | 90 |
Chinese | 小A | 88 |
Math | 小B | 70 |
English | 小B | 90 |
Chinese | 小B | 85 |
Math | 小C | 75 |
English | 小C | 95 |
Chinese | 小C | 85 |
Math | 小D | 80 |
English | 小D | 90 |
Chinese | 小D | 75 |
--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 |
Chinese | 88 | 85 | 85 | 75 |
English | 90 | 90 | 95 | 90 |
Math | 80 | 70 | 75 | 80 |
实现多行多列转换,请参考:http://www.cnblogs.com/hbwy/p/4359209.html