我构建了一个查询,它输出数千行,如:
| Person | Date | Hours1 | Hours2 |
Steve 2016 04 18 42.0
John 2016 04 21 32.09
Pete 2016 04 9 78.5
Steve 2016 03 10 10
Dave 2016 03 5 50
etc... etc... etc... etc...
但我需要:
|Person | 2016 04 Hours1 | 2016 04 Hours2 | 2016 03 Hours1 | 2016 03 Hours2 | etc...
Dave NULL NULL 5 50 etc...
John 21 32.09 NULL NULL etc...
Pete 9 78.5 NULL NULL etc...
Steve 18 42.0 10 10 etc...
etc... etc... etc... etc... etc... etc...
我已经用转置/旋转等方法研究了其他问题,但我不太确定这是否是一个简单的用例,因为有动态的日期和人数,但我真的不知道从哪里开始!
创建一个动态查询并执行它。
查询
declare @sql as varchar(max);
select @sql = 'select Person,' + stuff((
select distinct
',max(case [Date] when ''' + [Date] + ''' then Hours1 end) as [' + [Date] + ' Hours1]' +
',max(case [Date] when ''' + [Date] + ''' then Hours2 end) as [' + [Date] + ' Hours2]'
from Person
for xml path('')), 1, 1, '');
select @sql += ' from Person group by Person;';
exec(@sql);
结果
+--------+----------------+----------------+----------------+----------------+
| Person | 2016 03 Hours1 | 2016 03 Hours2 | 2016 04 Hours1 | 2016 04 Hours2 |
+--------+----------------+----------------+----------------+----------------+
| Dave | 5 | 50 | NULL | NULL |
| John | NULL | NULL | 21 | 32.09 |
| Pete | NULL | NULL | 9 | 78.5 |
| Steve | 10 | 10 | 18 | 42 |
+--------+----------------+----------------+----------------+----------------+
SQL Server中没有通用的透视功能。您要么需要创建一个动态SQL语句,要么需要处理客户端应用程序中的数据。