您可以PIVOT
为此使用 a,静态或动态。您可以将此代码放在存储过程中并用它填充您的数据网格。
Static Pivot(参见SQL Fiddle with Demo)这意味着您将对所有值进行硬编码:
select convert(char(10), dt, 101), [Bubai], [Bhanu], ([Bubai] + [Bhanu]) total
from
(
select dt, timelogged, username
from test
)x
pivot
(
sum(timelogged)
for username in ([Bubai], [Bhanu])
)p
union all
select 'total', sum([Bubai]), sum([Bhanu]), sum([Bubai] +[Bhanu])
from
(
select dt, timelogged, username
from test
)x
pivot
(
sum(timelogged)
for username in ([Bubai], [Bhanu])
)p
Dynamic Pivot(参见SQL Fiddle with Demo),这将获得在运行时转换的字段列表:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@totalCol AS NVARCHAR(MAX),
@totalRow AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.username)
FROM test c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @totalCol = STUFF((SELECT distinct '+' + QUOTENAME(c.username)
FROM test c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @totalRow = STUFF((SELECT distinct ',Sum(' + QUOTENAME(c.username) + ')'
FROM test c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT convert(char(10), dt, 101), ' + @cols + ', '+@totalCol +' total from
(
select dt, timelogged, username
from test
) x
pivot
(
sum(timelogged)
for username in (' + @cols + ')
) p
union all
select ''total'', '+ @totalRow +', sum('+@totalCol+')
from
(
select dt, timelogged, username
from test
)x
pivot
(
sum(timelogged)
for username in (' + @cols + ')
)p'
execute(@query)
这两者都会产生相同的结果。