0

我有一个 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

关于如何做到这一点的任何建议?谢谢。

4

2 回答 2

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;
于 2013-04-02T21:04:56.087 回答
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

请参阅SQL Fiddle with Demo

或者你可以在你的表上使用多个连接:

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'

请参阅带有演示的 SQL Fiddle

于 2013-04-02T21:08:09.843 回答