您可以获得所需的结果,但由于您需要在多列 (TaskDate1
和TaskDate2
) 上进行 PIVOT,因此我首先将两列取消旋转为多行。
由于您使用的是 SQL Server 2008+,因此您可以使用 UNPIVOT 函数或 CROSS APPLY 来转换多个列。基本语法将是:
select projectid,
col = TaskType+col,
value
from yourtable
cross apply
(
values
('Date1', TaskDate1),
('Date2', TaskDate2)
) c(col, value)
请参阅SQL Fiddle with Demo。这会将您的数据转换为易于使用的格式:
| PROJECTID | COL | VALUE |
|-----------|------------|------------------------------|
| 1 | Type4Date1 | April, 01 2013 00:00:00+0000 |
| 1 | Type4Date2 | May, 06 2013 00:00:00+0000 |
| 1 | Type0Date1 | April, 12 2013 00:00:00+0000 |
| 1 | Type0Date2 | May, 08 2013 00:00:00+0000 |
获得这种格式的数据后,您可以将 PIVOT 函数应用于 get max(value)
for each col
:
select projectId,
Type0Date1, Type0Date2,
Type2Date1, Type2Date2,
Type4Date1, Type4Date2
from
(
select projectid,
col = TaskType+col,
value
from yourtable
cross apply
(
values
('Date1', TaskDate1),
('Date2', TaskDate2)
) c(col, value)
) d
pivot
(
max(value)
for col in (Type0Date1, Type0Date2, Type2Date1, Type2Date2,
Type4Date1, Type4Date2)
) piv;
请参阅SQL Fiddle with Demo。
如果每个项目的值数量有限,上述版本会很好用ProjectId
,但如果每个项目的任务数量未知,则需要使用动态 SQL 来获得最终结果:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(TaskType+col)
from yourtable
cross apply
(
select 'Date1', 1 union all
select 'Date2', 2
) c(col, so)
group by col, tasktype, so
order by tasktype, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT projectid, ' + @cols + '
from
(
select projectid,
col = TaskType+col,
value
from yourtable
cross apply
(
values
(''Date1'', TaskDate1),
(''Date2'', TaskDate2)
) c(col, value)
) x
pivot
(
max(value)
for col in (' + @cols + ')
) p '
execute sp_executesql @query
请参阅SQL Fiddle with Demo。这些将给出结果:
| PROJECTID | TYPE0DATE1 | TYPE0DATE2 | TYPE2DATE1 | TYPE2DATE2 | TYPE4DATE1 | TYPE4DATE2 |
|-----------|------------------------------|----------------------------|------------------------------|----------------------------|------------------------------|----------------------------|
| 1 | April, 12 2013 00:00:00+0000 | May, 08 2013 00:00:00+0000 | April, 20 2013 00:00:00+0000 | May, 17 2013 00:00:00+0000 | April, 01 2013 00:00:00+0000 | May, 06 2013 00:00:00+0000 |