计算两次之间的时差(使用下一个特定ID)

时间:2014-03-21 19:59:55

标签: sql sql-server tsql sql-server-2012

以下是该表的示例:

ProductID    TransID    TransSubID    TimeID (HH:MM:SS)
111          58           2           10:00:00 
251          185         10           11:00:00
111          80           0           12:00:00
538          117          1           13:00:00
111          80           0           14:00:00

我需要一个查询来返回ProductID 111TransID 58TransSubID 2ProductID 111,{{1}的下一条记录之间TransID 80的已用时间}}。正确的结果是TransSubID 02 hours不正确。

3 个答案:

答案 0 :(得分:2)

这可以让你到达同一行中的下一个timeid值,从这里减去start_time和End_time值...

    SELECT 
    ProductID 
    ,TransID 
    ,TransSubID
    , TIMEID START_TIME
    , Lead(TIMEID,1,0) OVER(Partition BY ProductID ORDER BY transid,TransSubID , TIMEID) END_TIME
    FROM your_table
order by ProductID,TransID,TransSubID 

答案 1 :(得分:0)

UNTESTED:

SELECT A.ProductID, A.TransID, A.TransSubID, B.timeID-A.TimeID 
FROM TableName A
INNER JOIN tableName B 
ON A.Product_ID = B.Product_ID
  AND A.TransID < B.TransID
  AND A.timeID < B.TimeID
  And B.TimeID = (SELECT min(timeID) 
                  FROM tableName 
                  WHERE ProductID = B.ProductID 
                    and TransID = B.TransID)

答案 2 :(得分:0)

考虑将TIMEFROMPARTS行中的逻辑放入Function中。我使用第二个CROSS APPLY只是为了让我的秒数变成一个更简单的形式,它在TIMEFROMPARTS函数中使用了3次。

SELECT t.ProductID, t.TransID, t.TransSubID, t.TimeID, 
        t2.TransID, t2.TransSubID, t2.TimeID, 
        DATEDIFF(HOUR, t.TimeID, t2.TimeID) 'IfYouWantHours',
        DATEDIFF(MINUTE, t.TimeID, t2.TimeID) 'IfYouWantMinutes',
        TIMEFROMPARTS(d.seconds % 216000 / 3600, d.seconds % 216000 % 3600 / 60
            , d.seconds % 3600 % 60, 0,0) 'IfYouWantTime'
FROM tblTransit t
    -- Returns the first (based on the time) record with the same ProductID
    -- and TimeID greater than.
    CROSS APPLY (SELECT TOP 1 ProductID, TransID, TransSubID, TimeID 
                FROM tblTransit 
                WHERE ProductID = t.ProductID 
                    AND TimeID > t.TimeID) t2
    CROSS APPLY (SELECT DATEDIFF(SECOND, t.TimeID, t2.TimeID) seconds) d

...返回

   ProductID   TransID     TransSubID  TimeID           TransID     TransSubID  TimeID           IfYouWantHours IfYouWantMinutes IfYouWantTime
----------- ----------- ----------- ---------------- ----------- ----------- ---------------- -------------- ---------------- ----------------
111         58          2           10:00:00.0000000 80          0           12:00:00.0000000 2              120              02:00:00
111         80          0           12:00:00.0000000 80          0           14:00:00.0000000 2              120              02:00:00