我构建了一个输出数千行的查询,如:
| 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...
我已经使用转置/旋转来查看其他问题等但我不太确定这是一个简单的用例,因为有动态的日期和人数,但我我真的不知道从哪里开始!
答案 0 :(得分:3)
创建动态查询并执行它。
<强>查询强>
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 |
+--------+----------------+----------------+----------------+----------------+
答案 1 :(得分:0)
SQL Server中没有通用的数据透视功能。您需要创建动态SQL语句,或者需要处理客户端应用程序中的数据。