2015-07-01 68 views
0

我有SQL Server 2008中票證歷史記錄的日誌表。這裏我有datetime和Status字段。我必須計算我花在這張票上的總時間。 在這裏,我必須計算從接受狀態到結束狀態的總時間,並且必須排除未決的供應商狀態需要計算在SQL Server 2008中花費的票據總時間量

time(datediff(minute,'2015-06-19 16:03:13.000', '2015-06-22 06:32:31.000')+datediff(minute,'2015-06-22 11:15:15.000', '2015-06-23 10:15:15.000'))

而且我有2周以上的狀態

例子:

'ticket_number Date & Time    Problem Status 
    16676  2015-06-19 15:50:14.000  Open 
    16676  2015-06-19 15:50:14.000  Accepted 
    16676  2015-06-19 15:50:44.000  Work in progress 
    16676  2015-06-19 16:03:13.000  Pending Vendor 
    16676  2015-06-22 06:32:31.000  Work in progress 
    16676  2015-06-22 11:15:15.000  Pending Vendor 
    16676  2015-06-23 10:15:15.000  Work in progress 
    16676  2015-06-23 10:15:15.000  Closed' 

回答

2

您可以使用CROSS APPLYGROUP BY這樣。

查詢

SELECT t1.ticket_number,SUM(DATEDIFF(second,DateTime,CloseTime)) as TotalSeconds 
FROM tickets t1 
CROSS APPLY(SELECT TOP 1 DateTime as CloseTime FROM tickets t2 WHERE t1.ticket_number = t2.ticket_number and t2.id > t1.id ORDER BY t2.DateTime) as t2 
WHERE t1.ProblemStatus <> 'Pending Vendor' 
GROUP BY t1.ticket_number 

輸出

| ticket_number | TotalSeconds | 
|---------------|--------------| 
|   16676 |  17743 | 
相關問題