MS SQL 的新手,必须找出同一列第一行和第二行的小时数差异

new to MS SQL, have to find difference in hours of first and second row of same column

例如。比较第一行和第二行invoice_status_change_datetime,直到它进入不同的状态,必须捕获以小时为单位的持续时间。

**AP_WORK_ID    INVOICE_STATUS  INVOICE_STATUS_CHANGE_DATETIME   LAST_UPDATED_USER**
  1060565       Assigned        **2020-01-27 07:17:57.837**          xxxxxx
  1060565       Assigned        **2020-01-27 10:17:57.837**          yyyyyy
  1060565       In Progress       2020-01-29 01:08:56.943            xxxxxx
  1060565       Rejected          2020-01-28 07:17:57.837            xxxxxx
  1060565       Hold              2020-01-28 10:17:57.837            yyyyyy
  1060565       Closed            2020-01-29 01:08:56.943            xxxxxx

但结果应该如下所示,因为我想将此结果与其他连接条件合并

**AP_WORK_ID    Assigned_hrs  In Progress_hrs  Query_Resolved_hrs Rejected_hrs hold_hrs closed_hrs**
  1060565       24            3 hrs            null               10hrs        5hrs     null

我尝试了使用 lead() 的代码,我也在 hrs 中得到了输出,但我不知道如何转换为上述格式:

SELECT isc.INVOICE_STATUS,
    isc.INVOICE_STATUS_CHANGE_DATETIME,
    DATEDIFF(HH, isc.INVOICE_STATUS_CHANGE_DATETIME, LEAD(isc.INVOICE_STATUS_CHANGE_DATETIME) OVER(
    ORDER BY isc.INVOICE_STATUS_CHANGE_DATETIME)) AS status_change_Hours       
FROM INVOICE_STATUS_CHANGE ISC
where isc.AP_WORK_ID = 1060565
GROUP BY isc.INVOICE_STATUS, isc.INVOICE_STATUS_CHANGE_DATETIME

我理解这个有点复杂,有没有精通SQL的人知道如何实现这个

我在考虑lead()和条件聚合:

select
    ap_work_id,
    sum(case when invoice_status = 'Assigned'    
        then datediff(hour, change_dt, next_change_dt) end) assigned_hrs,
    sum(case when invoice_status = 'In Progress' 
        then datediff(hour, change_dt, next_change_dt) end) in_progress_hrs,
    sum(case when invoice_status = 'Rejected'
        then datediff(hour, change_dt, next_change_dt) end) rejected_hrs,
    sum(case when invoice_status = 'Hold' 
        then datediff(hour, change_dt, next_change_dt) end) hold_hrs,
    sum(case when invoice_status = 'Closed' 
        then datediff(hour, change_dt, next_change_dt) end) closed_hrs
from (
    select 
        ap_work_id,
        invoice_status,
        invoice_status_change_datetime change_dt,
        lead(invoice_status_change_datetime) 
            over(partition by ap_work_id order by invoice_status_change_datetime) next_change_dt
    from mytable t
) t
group by ap_work_id

Demo on DB Fiddle:

ap_work_id | assigned_hrs | in_progress_hrs | rejected_hrs | hold_hrs | closed_hrs
---------: | -----------: | --------------: | -----------: | -------: | ---------:
   1060565 |           18 |               6 |            3 |       15 |       null

结果与您显示的略有不同(我不得不修正状态为已分配的行上的日期,这与其余数据不一致),但我认为这些实际上是正确的您的示例数据。