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、各イベントの時間を示す 1 行の結果を表示することです。

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

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 に答える
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 に答える