PiVot 用法
基本语法:
SELECT <非透视的列>,
[第一个透视的列] AS <列名称>,
[第二个透视的列] AS <列名称>,
...
[最后一个透视的列] AS <列名称>,
FROM
(<生成数据的 SELECT 查询>)
AS <源查询的别名>
PIVOT
(
<聚合函数>(<要聚合的列>)
FOR
[<包含要成为列标题的值的列>]
IN ( [第一个透视的列], [第二个透视的列],
... [最后一个透视的列])
) AS <透视表的别名>
<可选的 ORDER BY 子句>;
例子:
create table T3
(
Year Nvarchar(10),
Mounth Nvarchar(10),
Day Nvarchar(10)
)
insert into T3 values ('1991','3','1.3')
insert into T3 values ('1991','4','1.4')
insert into T3 values ('1992','1','2.1')
insert into T3 values ('1992','2','2.2')
insert into T3 values ('1992','3','2.3')
insert into T3 values ('1992','4','2.4')
select * from T3
数据如图所示:
select * from T3
select Year as Year , [1],[2],[3],[4] from (select * from T3) As t3
pivot
(
max(day) for mounth in ([1],[2],[3],[4] )
)
as PivotTable