2017-03-29 38 views
0

我有以下格式化的表數據值。我想要獲得上一次操作完成狀態的開始時間和結束時間,需要在下次準備就緒操作中顯示。如何讓以前的EndTime在新行中計算?

E.g:原始表格式:

 Sno Operation  Status    StartTime    EndTime  
    ------ ----------- -----------------  --------------------- --------------- 
    1  OP10  Complete    2017-03-01 07:00:00 2017-03-01 07:10:00 
    1  OP20  Complete    2017-03-01 07:10:00 2017-03-01 07:30:00 
    1  OP30  Ready      Null     Null 
    2  OP10  Complete    2017-03-01 08:00:00 2017-03-01 08:10:00 
    2  OP20  Ready      Null     Null 
    3  OP10  Complete    2017-03-01 09:00:00 2017-03-01 09:10:00 
    3  OP20  Complete    2017-03-01 10:00:00 2017-03-01 10:10:00 
    3  OP30  Ready     2017-03-01 10:00:00 2017-03-01 10:10:00 

我需要的輸出是這樣的:

Sno  Operation  Status   TotalDurationCountInMins  
------ ------------ ------------ --------------------------------- 
    1  OP30  Ready      20  
    2  OP20  Ready      10 
    3  OP30  Ready      10 

回答

0

使用子查詢來獲得最後的操作完成時間。

注:如果你的工作列包含不能排序的數據(如「開始」,「中等」,「結束」)這個查詢將產生錯誤結果。

(保存我們在你未來的問題,這一步)創建和填充示例表

DECLARE @T AS TABLE 
(
    Sno int, 
    Operation char(5), 
    [Status] varchar(8), 
    StartTime datetime, 
    EndTime datetime 
) 

INSERT INTO @T VALUES 
(1, 'OP10', 'Complete', '2017-03-01 07:00:00', '2017-03-01 07:10:00'), 
(1, 'OP20', 'Complete', '2017-03-01 07:10:00', '2017-03-01 07:30:00'), 
(1, 'OP30', 'Ready', Null, Null), 
(2, 'OP10', 'Complete', '2017-03-01 08:00:00', '2017-03-01 08:10:00'), 
(2, 'OP20', 'Ready', Null, Null), 
(3, 'OP10', 'Complete', '2017-03-01 09:00:00', '2017-03-01 09:10:00'), 
(3, 'OP20', 'Complete', '2017-03-01 10:00:00', '2017-03-01 10:10:00'), 
(3, 'OP30', 'Ready', '2017-03-01 10:00:00', '2017-03-01 10:10:00') 

查詢:

SELECT Sno, 
     Operation, 
     [Status], 
     (SELECT TOP 1 DATEDIFF(MINUTE, StartTime, EndTime) 
     FROM @T t2 
     WHERE t2.Sno = t1.Sno 
     AND t2.Operation < t1.Operation 
     AND t2.[Status] = 'Complete' 
     ORDER BY StartTime DESC 
     ) AS TotalDurationCountInMins 
FROM @T t1 
WHERE [Status] = 'Ready' 

結果:

Sno  Operation Status TotalDurationCountInMins 
1  OP30  Ready 20 
2  OP20  Ready 10 
3  OP30  Ready 10 

See a live demo on rextester

+0

很多感謝......工作完美。 – Dhamo

相關問題