开发者

microsoft sql server datediff for multiple dates

I need to find the length of time between 2 dates (datetime types) based on the unique ID. For example, I have the following data:

ID                 CallID                         Starttime                   
1                  56                             2011-01-04 10:00:00.000
1                  67                             2011-03-20 12:20:00.000
1                  70                             2011-04-08 15:00:00.000
2                  57                             2011-01-14 11:00:00.000
2                  62                             2011-02-14 11:00:00.000
2                  64                             2011-02-15 11:00:00.000
2                  75                             2011-04-14 11:00:00.000
2                  78                             2011-05-14 11:00:00.000

I need to fin开发者_如何学Pythond the length of time for all the CallIDs for each ID based on the previous call date (starttime). For example, I need the length of time for all the calls for ID 1 (CallID 67 - CallID 56 and CallID 70 - CallID 67, etc.).

I know I need a loop of some kind that would go through the IDs to find the CallIDs for that ID but do I also need a temporary table where I would organize the CallIDs?

Any suggestions would be appreciated. Thank you.


One way.

;WITH T
     AS (SELECT ID,
                CallID,
                Starttime,
                ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Starttime) RN
         FROM   YourTable)
SELECT t1.ID,
       t1.CallID,
       t2.CallID,
       DATEDIFF(HOUR, t1.Starttime, t2.Starttime)
FROM   T t1
       INNER JOIN T t2
         ON t1.RN = t2.RN - 1
            AND t1.ID = t2.ID  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜