用十进制输出SQL Server 2008减去下一行的列值

时间:2018-07-11 17:45:00

标签: sql sql-server sql-server-2008 tsql

每次状态为“已审阅”且ID编号相同(按ID分组)时,我都希望检索十进制数字中的天数。

Audit_Event的外观如下:

ID           STATUS           EVENT_DATE
--           ------           ----------
1012         Fastrack         2018-05-24 10:07:46.560
1000         Reviewed         2018-05-25 12:35:07.023
1000         Declined         2018-06-15 21:02:32.567
1234         Cancelled        2018-05-01 13:00:35.257
1000         Reviewed         2018-06-16 10:46:41.607
1000         Completed        2018-06-20 13:08:27.697
2135         Approved         2018-06-20 16:18:27.240
1000         Cancelled        2018-06-27 15:11:33.930 
1035         Lead             2018-04-02 13:35:51.817
1000         Pre-Approval     2018-04-02 13:32:57.120       

以ID为例= 1000,状态=已审核:

(2018-06-15 21:02:32.567 - 2018-05-25 12:35:07.023) + (2018-06-20 13:08:27.697 - 2018-06-16 10:46:41.607) = 25.45 (Days)

因此输出应为:

ID            Number_Days
--------      ---------
1012           NULL
1000           25.45
1234           NULL
2135           NULL

这是我现在正在使用的查询:

IF OBJECT_ID(N'tempdb..#Reviewed_Table', N'U') IS NOT NULL  
    DROP TABLE #Reviewed_Table   

CREATE TABLE #Reviewed_Table
(
    RN INT,
    ID VARCHAR(50),
    EVENT_DATE DATETIME,
    STATUS VARCHAR(500)
)

INSERT INTO #Reviewed_Table
    SELECT 
        ROW_NUMBER() OVER (ORDER BY ID) RN, 
        ID, EVENT_DATE, STATUS
    FROM 
        Audit_Event 


SELECT 
    T1.ID, 
    CONVERT(DECIMAL(16, 4), (SUM(DATEDIFF(DAY, T1.Event_Date, T2.Event_Date)))) Rev_Days
FROM 
    #Reviewed_Table T1  
LEFT JOIN 
    #Reviewed_Table T2 ON T1.RN = T2.RN -1
WHERE 
    T1.STATUS = 'Reviewed' 
GROUP BY 
    T1.ID

注意:我不能使用LEADLAG,因为这是一台SQL Server 2008计算机。

如果状态不同于Reviewed,则应为NULL。审查的状态可能超过2,并且可能的状态更多。

任何帮助或帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果仅查看下一条记录,则可以使用cross apply

select rt.id,
       ( datediff(second, rt.event_date, rt2.event_date) / (24 * 60 * 60.0) ) as number_days
from #Reviewed_Table rt outer apply
     (select top (1) rt2.*
      from #Reviewed_Table rt2
      where rt2.id = rt.id and rt2.event_date > rt.event_date
      order by rt2.event_date asc
     ) rt2
where rt.status = 'Reviewed'
group by rt.id;