您可以使用 PIVOT 执行此操作, 要么是静态 PIVOT, 硬代码为年数, 要么是动态 PIVOT, 用来创建运行查询的年份列表 :
静态脉搏:
create table table1
(
totalhours decimal(10, 2),
year int
)
insert into table1 values(100, 2012)
insert into table1 values(200, 2012)
insert into table1 values(300, 2012)
insert into table1 values(75, 2011)
insert into table1 values(150, 2011)
insert into table1 values(50, 2010)
insert into table1 values(125, 2010)
select *
from
(
select *
from table1
) x
pivot
(
sum(totalhours)
for year in ([2012], [2011], [2010])
) p
< a href=" "http://sqlfiddle.com/#! 3/b2fe2/2/1, rel=" noreferrer" > 这里有一个 SQL 中小插曲
动态枢纽 :
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct , + QUOTENAME(c.year)
FROM table1 c
FOR XML PATH( ), TYPE
).value( . , NVARCHAR(MAX) )
,1,1, )
set @query = SELECT + @cols + from
(
select totalhours, year
from table1
) x
pivot
(
sum(totalhours)
for year in ( + @cols + )
) p
execute(@query)
两者的结果都一样