我有一个表,其中包含更改维护服务状态的事件。这是一个数据样本:
id date event
234 2009-04-22 10:00:00 Service Request
234 2009-04-22 10:02:00 Service Approbation
234 2009-04-22 10:03:00 Service Asignation
234 2009-04-22 10:40:00 Service Fulfilled
...
在报告中,我需要显示在每个项目上花费的时间
id time
234 40 minutes
235 37 minutes
...
基本上,我正在做这样的 DATEDIFF:
SELECT ...
, DATEDIFF(SECOND,
(SELECT TOP 1 date FROM event_table ev WHERE ev.item = itm.id AND event = 1 ORDER BY date ),
(SELECT TOP 1 date FROM event_table ev WHERE ev.item = itm.id AND event = 4 ORDER BY date DESC)
), ...
FROM item_table itm
WHERE ...
现在我必须实现一个新的状态。延迟和重新激活服务,但在计算花费在该服务上的总时间时不必考虑这些时间。
id date event
234 2009-04-22 10:00:00 Service Request
234 2009-04-22 10:02:00 Service Approbation
234 2009-04-22 10:03:00 Service Asignation
234 2009-04-22 10:07:00 Service Delayed -- new state
234 2009-04-22 10:37:00 Service Reactivated -- new state
234 2009-04-22 10:40:00 Service Fulfilled
...
报告
id time
234 10 minutes -- Substract 30 minutes between Delay and Reactivation
235 26 minutes
...
对于任何项目,延迟和重新激活都可能发生多次。
我知道我可以用光标来做到这一点,但对我来说这似乎很老套,有没有办法在基于集合的方法上计算这个?