查询以在不同行的字段之间执行DATEDIFF

时间:2019-05-09 15:31:53

标签: sql sql-server

我需要在查询中添加一个DATEDIFF,以便为我提供当前行字段和上一行相同字段之间的小时数。

编辑:{我应该通过ROUTED_DTM DESC对整个查询进行排序,还是在DATEDIFF DESC中进行ORDER BY?

在一行中,我的ROUTED_DTM为'2019-05-07 15:36:13.000',在上一行中的ROUTED_DTM为'2019-05-01 14:19:52.000'。我希望AGE_IN_ROLE_DAY,AGE_IN_ROLE_HR,AGE_IN_ROLE_MIN,AGE_IN_ROLE_SEC分别为6、1、16和21。但是,我得到0、0、0,-2。}

SELECT c.ID,
       c.PAID_DT,
       DATEDIFF(dd,
                CASE WHEN c.ID_ADJ_FROM = '' THEN c.RECD_DT ELSE c.INPUT_DT END,
                CASE WHEN c.PAID_DT = '1/1/1753' THEN CONVERT(DATE,GETDATE()) ELSE c.PAID_DT END) + 1 AS DAYS_OLD
       DATEDIFF(dd, h.ROUTED_DTM, LAG(h.ROUTED_DTM) OVER (ORDER BY h.ROUTED_DTM DESC)) AS AGE_IN_ROLE_DAY,
       DATEDIFF(hh, h.ROUTED_DTM, LAG(h.ROUTED_DTM) OVER (ORDER BY h.ROUTED_DTM DESC)) AS AGE_IN_ROLE_HR,
       DATEDIFF(MM, h.ROUTED_DTM, LAG(h.ROUTED_DTM) OVER (ORDER BY h.ROUTED_DTM DESC)) AS AGE_IN_ROLE_MIN,
       DATEDIFF(ss, h.ROUTED_DTM, LAG(h.ROUTED_DTM) OVER (ORDER BY h.ROUTED_DTM DESC)) AS AGE_IN_ROLE_SEC,
       h.QUEUE_ID,
       h.QUEUE_DESC,
       h.ROLE_ID,
       h.ROLE_DESC,
       h.ROUTED_DTM

FROM table1 c
LEFT JOIN table2 h
    ON h.ID = c.ID
LEFT JOIN table 3 q
    ON q.QUEUE_ID = h.QUEUE_ID
LEFT JOIN table4 r
    ON r.ROLE_ID = h.ROLE_ID

ORDER BY c.ID, h.ROUTED_DTM DESC

我想在h.QUEUE_ID列之前添加一个DATEDIFF,以给出当前行的h.ROUTED_DTM与上一行的h.ROUTED_DTM之间的差异

当前,查询返回正确的结果,但是,我不确定如何向每行添加新的DATEDIFF。

1 个答案:

答案 0 :(得分:0)

您可以使用lag()

datediff(day, routed_dtm, lag(routed_dtm) over (order by routed_dtm))

您可能还希望在窗口子句中使用partition by c.id