如何找到两行中存在的数据之间的时差

时间:2016-06-20 10:02:50

标签: sql sql-server

我有以下table

Customer_ID PurchaseDatetime
309         2/3/2014  12:29:00
309         2/27/2014 17:11:00
309         4/15/2014 13:24:00

我想编写一个查询来计算两个连续行的datetime字段之间的差异。理想情况下,输出应该像

Customer_ID PurchaseDatetime
309         0
309         2/27/2014 17:11:00 - 2/3/2014  12:29:00 // The exact time difference in hours
309         4/15/2014 13:24:00 - 2/27/2014 17:11:00 // The exact time difference in hours

如何撰写此类查询?

3 个答案:

答案 0 :(得分:3)

试试这个......

CREATE TABLE #Purchases
(
    CustomerID     INT,
    PurchaseDate   DATETIME
)
INSERT INTO #Purchases
VALUES
(100004,'2016-05-16 08:00:00'),
(100005,'2016-05-16 09:05:00'),
(100006,'2016-05-16 10:08:40'),
(32141 ,'2016-05-16 11:18:00'),
(84230 ,'2016-05-16 12:25:10'),
(23444 ,'2016-05-16 13:40:00'),
(100001,'2016-05-16 14:50:00')

;WITH CTE AS
(
    SELECT
    CustomerID,
    PurchaseDate,
    ROW_NUMBER() OVER (ORDER BY PurchaseDate) AS Seq
    FROM #Purchases
)
SELECT
    p.CustomerID,
    p.PurchaseDate,
    pl.PurchaseDate,
    DATEADD(SECOND,DATEDIFF(SECOND, pl.PurchaseDate,p.PurchaseDate),0) AS DiffDT,
DATEDIFF(HOUR, pl.PurchaseDate,p.PurchaseDate) HourDiff
FROM CTE AS p
LEFT OUTER JOIN CTE AS pl ON pl.Seq = p.Seq - 1 -- Last batch   
ORDER BY p.PurchaseDate

答案 1 :(得分:0)

尝试此查询...

    ;with cte as
    (select row_number() over(order by (select 100)) Id.Customer_ID,PurchaseDatetime from Table)
    select a.Customer_ID,b.PurchaseDatetime-a.PurchaseDatetime from cte a inner join cte b on a.id=b.id-1

由于

答案 2 :(得分:-1)

   SELECT *,
    PURCHASEDATETIME = 
    CASE CUSTOMER_ID 
        WHEN CUSTOMER_ID THEN 
            DATEDIFF(HH, LAG(PURCHASEDATETIME, 1) OVER(ORDER BY CUSTOMER_ID, PURCHASEDATETIME), PURCHASEDATETIME)
        ELSE 
            NULL
    END 
    FROM table