我有一个SQL Server 2005表,记录了流程的每个步骤,如下所示
ResourceID EventType Time
ABC123 Job Activated 2013-01-08 10:01:31.000
ABC123 Download Complete 2013-01-08 10:03:32.000
ABC123 Job Complete 2013-01-08 10:07:42.000
XYZ789 Job Activated 2013-01-08 12:05:11.000
XYZ789 Download Complete 2013-01-08 12:08:52.000
XYZ789 Job Complete 2013-01-08 12:14:21.000
我想要做的是显示每个ResourceID
一行的结果,显示每个事件的时间。
ResourceID Job Activated Download Complete Job Complete
ABC123 2013-01-08 10:01:31.000 2013-01-08 10:03:32.000 2013-01-08 10:07:42.000
XYZ789 2013-01-08 12:05:11.000 2013-01-08 12:08:52.000 2013-01-08 12:14:21.000
有关如何完成此任务的任何建议?感谢。
答案 0 :(得分:2)
正如评论建议的那样,您可以使用PIVOT
轻松完成此操作:
DECLARE @x TABLE(ResourceID CHAR(6), EventType VARCHAR(32), [Time] DATETIME);
INSERT @x SELECT 'ABC123','Job Activated ','2013-01-08 10:01:31.000'
UNION ALL SELECT 'ABC123','Download Complete','2013-01-08 10:03:32.000'
UNION ALL SELECT 'ABC123','Job Complete ','2013-01-08 10:07:42.000'
UNION ALL SELECT 'XYZ789','Job Activated ','2013-01-08 12:05:11.000'
UNION ALL SELECT 'XYZ789','Download Complete','2013-01-08 12:08:52.000'
UNION ALL SELECT 'XYZ789','Job Complete ','2013-01-08 12:14:21.000';
SELECT ResourceID,[Job Activated],[Download Complete],[Job Complete]
FROM @x
PIVOT
(
MAX([Time]) FOR EventType IN (
[Job Activated],[Download Complete],[Job Complete]
)) AS p;
答案 1 :(得分:2)
您可以使用带有CASE
表达式的聚合函数来旋转数据:
select resourceid,
max(case when EventType = 'Job Activated' then [time] end) as [Job Activated],
max(case when EventType = 'Download Complete' then [time] end) as [Download Complete],
max(case when EventType = 'Job Complete' then [time] end) as [Job Complete]
from yourtable
group by resourceid
或者您可以在桌面上使用多个联接:
select ja.resourceid,
ja.[time] as [Job Activated],
dc.[time] as [Download Complete],
jc.[time] as [Job Complete]
from yourtable ja
left join yourtable dc
on ja.resourceid = dc.resourceid
and dc.EventType = 'Download Complete'
left join yourtable jc
on ja.resourceid = jc.resourceid
and jc.EventType = 'Job Complete'
where ja.EventType = 'Job Activated'