首先,一种方法:
create table #tab (
Username nvarchar(100),
[Date] date,
[hours] numeric(8,1)
)
insert #tab values
('John', '1995-02-01', 45),
('John', '1995-02-01', 16),
('Nancy', '1998-03-01', 25),
('John', '2001-05-01', 35.5),
('Peter', '1995-02-01', 46),
('Bill', '2001-05-01', 48),
('Bill', '1995-02-01', 56)
select pvt.*
from (
select Username,
datename(month, [Date]) + ' ' + convert(nvarchar(20), datepart(year, [Date])) [Date],
[hours]
from #tab
) t
pivot (
SUM([hours])
for [Date] in ([February 1995], [March 1998], [May 2001])
) pvt
drop table #tab
现在,您可能需要这样做:
create table #tab (
Username nvarchar(100),
[Date] date,
[hours] numeric(8,1)
)
insert #tab values
('John', '1995-02-01', 45),
('John', '1995-02-01', 16),
('Nancy', '1998-03-01', 25),
('John', '2001-05-01', 35.5),
('Peter', '1995-02-01', 46),
('Bill', '2001-05-01', 48),
('Bill', '1995-02-01', 56)
declare @columns nvarchar(max) = ''
declare @sql nvarchar(max) = ''
declare @delim nvarchar(10) = ''
select @columns = @columns + @delim + '[' + x.[Date] + ']',
@delim = ', '
from (
select datename(month, t.[Date]) + ' ' + convert(nvarchar(20), datepart(year, t.[Date])) [Date],
datepart(year, t.[Date]) [Year],
datepart(month, t.[Date]) [Month]
from #tab t
) x
group by x.[Date]
order by MAX(x.[Year]), MAX(x.[Month])
select @columns
set @sql = '
select pvt.Username,
' + @columns + '
from (
select Username,
datename(month, [Date]) + '' '' + convert(nvarchar(20), datepart(year, [Date])) [Date],
[hours]
from #tab
) t
pivot (
SUM([hours])
for [Date] in (' + @columns + ')
) pvt
'
exec(@sql)
drop table #tab
问题是 PIVOT 不允许您动态指定生成的列...您必须知道要执行此操作的列中的内容。解决方案是创建具有不同列的动态 SQL,然后在此基础上构建一个数据透视语句。