添加此作爲單獨的答案,因爲方法是完全不同的。很肯定這是你在找什麼:
-- Create table for sample data
Create table #tickets
( ticket_number int
, dateTime_status datetime
, ProblemStatus nvarchar(50)
)
-- Insert sample data into temp table
Insert into #tickets
Values (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')
, (16677, '2015-06-19 15:50:14.000', 'Open')
, (16677, '2015-06-20 15:50:14.000', 'Accepted')
, (16677, '2015-06-20 15:50:44.000', 'Work in progress')
, (16677, '2015-06-20 16:03:13.000', 'Pending Vendor')
, (16677, '2015-06-23 06:32:31.000', 'Work in progress')
, (16677, '2015-06-23 11:15:15.000', 'Pending Vendor')
, (16677, '2015-06-24 10:15:15.000', 'Work in progress')
, (16677, '2015-06-25 10:15:15.000', 'Closed')
-- Select time difference for status from and to per ticket
-- Time difference is measured in minutes. Change the datepare to desired unit if required.
Select ROW_NUMBER() over(partition by a.ticket_number order by a.RowNum)
, a.ticket_number
, a.ProblemStatus as 'Status_from'
, b.ProblemStatus as 'Status_to'
, DATEDIFF(MINUTE,a.dateTime_status,b.dateTime_status) as 'Time_in_minutes'
from
-- Nested select to set subsequent events side by side. Add row numbers.
(Select ROW_NUMBER() over(partition by ticket_number order by dateTime_status) as 'RowNum'
, ticket_number
, dateTime_status
, ProblemStatus
from #tickets) as A
-- Join first nested query on second one with same data, but join on b.rownum = a.rownum + 1
-- This puts the event in B next to the previous event in A
inner join (Select ROW_NUMBER() over(partition by ticket_number order by dateTime_status) as 'RowNum'
, ticket_number
, dateTime_status
, ProblemStatus
from #tickets) as B
on a.ticket_number = b.ticket_number
and b.RowNum = a.RowNum + 1
-- Exclude records where the beginning status is "Pending Vendor"
where a.ProblemStatus <> 'Pending Vendor'
order by a.ticket_number
, a.RowNum
-- Drop the temp table
drop table #tickets
你基本上還加入相同的數據彼此爲2個獨立的數據集,但通過添加行號的數據,你可以加入1分表至第二個表中的下一行。這允許您並排設置順序事件,並計算它們之間的時間差。排除第一個表中的ProblemStatus爲「待定供應商」的任何記錄,並且您有實際的時間處理該問題。分鐘總數是您每張票的總時間。如果您需要更準確的時間測量,請將日期部分更改爲秒。然後很容易將其轉換爲秒,分鐘,小時格式。
編輯使問題更清楚。 –
請問哪個版本?從SQL Server 2012開始,您有這樣的查詢的'LAG'語句。 –