自动创建总差异比较行

时间:2019-12-09 07:11:26

标签: sql sql-server tsql

以下是一些示例数据,显示了具有特定ID的开始日期和结束日期的各种雕像。

enter image description here

“已用天数”列是特定行的datediff。

select 
    *,
    DateDiff(d,StartDate,EndDate) as DaysElapsed 
from 
    #Sample

我要尝试的是将特定ID的经过总天数与第一个StartDate和最大的结束日期进行比较。

对于ID 1,经过了22天(7 + 8 + 7),但是当您比较第一个开始日期(2019-11-01)和最后一个结束日期(2019-11-25) ,实际上是24。因此,我需要为ID 1添加另一行,其状态为“不正确的流量”,其“经过的天数”值为2。如果匹配,则不会添加任何行。

当记录的结束日期值为NULL时,它应该完全忽略该ID。因此预期结果将是:

enter image description here

样本数据

Create Table #Sample
(
    ID int,
    Status varchar(20),
    StartDate datetime,
    EndDate datetime
)

insert into #Sample
(
    ID,
    Status,
    StartDate,
    EndDate
)
select
    1,
    'Status 1',
    '01 Nov 2019',
    '08 Nov 2019'
union all
select
    1,
    'Status 2',
    '10 Nov 2019',
    '18 Nov 2019'
union all
select
    1,
    'Status 3',
    '18 Nov 2019',
    '25 Nov 2019'
union all
select
    2,
    'Status 1',
    '02 Nov 2019',
    '09 Nov 2019'
union all
select
    2,
    'Status 2',
    '16 Nov 2019',
    '29 Nov 2019'
union all
select
    2,
    'Status 3',
    '29 Nov 2019',
    '03 Dec 2019'
union all
select
    2,
    'Status 4',
    '03 Dec 2019',
    '08 Dec 2019'
union all
select
    3,
    'Status 1',
    '01 Dec 2019',
    '03 Dec 2019'
union all
select
    3,
    'Status 2',
    '03 Dec 2019',
    NULL

1 个答案:

答案 0 :(得分:2)

首先,您用incorrect Flow标识这些ID。您可以通过比较datediff(day, min(StartDate), max(EndDate))sum(datediff(day, StartDate, EndDate))

来完成此操作

之后,将JOIN#Sample一起返回结果。要显示多余的行Incorrect Flow,请使用UNION ALL

with err_id as
(
    select  ID, 
            DaysElapsed = datediff(day, min(StartDate), max(EndDate))
                        - sum(datediff(day, StartDate, EndDate))
    from    #Sample
    group by ID
    having  datediff(day, min(StartDate), max(EndDate))
    <>      sum(datediff(day, StartDate, EndDate))
)
select  s.*, DaysElapsed = datediff(day, StartDate, EndDate)
from    err_id e
        inner join #Sample s    on  e.ID    = s.ID

union all

select  ID, Status = 'Incorrect Flow', StartDate = NULL, EndDate = NULL, DaysElapsed 
from    err_id