【问题标题】:Cumulative Formula That Resets If Meets Criteria (SQL Server)满足条件时重置的累积公式 (SQL Server)
【发布时间】:2019-12-30 20:21:14
【问题描述】:

你好,新年快乐! 我有一个关于累积公式的问题,如果“最后一次 fd 之间的天数”超过 30 天,它将“重置”。示例如下。

首先是信息有限的测试温度。我不需要关于 f-sdays 或 Last fd 之间的天数的帮助。这只是 累积天数计算。我希望输出看起来像 @results

DECLARE @test table(ID int, startdate date, finishdate date) 
INSERT INTO @test(ID, startdate, finishdate) VALUES

(123, '2019-12-30', '2019-12-31'),
(123, '2019-11-15', '2019-12-10'),
(123, '2019-09-12', '2019-10-10'),
(123, '2019-09-02', '2019-09-09'),
(123, '2019-08-30', '2019-09-01'),

(789, '2019-11-30', '2019-12-31'),
(789, '2019-11-15', '2019-11-17'),
(789, '2019-09-12', '2019-10-10'),
(789, '2019-09-02', '2019-09-04'),
(789, '2019-08-30', '2019-09-01')


select *
from @test





DECLARE @results TABLE(ID int, startdate date, finishdate date   ,[F-SDays] int,  DaysBetweenLastFD int, cumulativeDays int) 
INSERT INTO @results(ID, startdate, finishdate, [F-SDays], DaysBetweenLastFD, cumulativeDays) VALUES

(123, '2019-12-30', '2019-12-31', 1, 20, 26),
(123, '2019-11-15', '2019-12-10', 25, 36, 25),
(123, '2019-09-12', '2019-10-10', 28, 3, 37),
(123, '2019-09-02', '2019-09-09', 7, 1, 9),
(123, '2019-08-30', '2019-09-01', 2, 0, 2),

(789, '2019-11-30', '2019-12-31', 31, 13, 33),
(789, '2019-11-15', '2019-11-17', 2, 36, 2),
(789, '2019-09-12', '2019-10-10', 28, 8, 32),
(789, '2019-09-02', '2019-09-04', 2, 1, 4),
(789, '2019-08-30', '2019-09-01', 2, 0, 2)


select *
from @results

【问题讨论】:

    标签: sql-server sum lag partition case-when


    【解决方案1】:

    如果“上次 fd 之间的天数”超过 30,则设置新组标志。对 newgroupflags 求和(直到当前行)将识别每行的当前组/序号。将每个 ID 和 groupordinal 的 datediff 相加将给出重置运行总数:

    select *, sum(datediff(day, startdate, finishdate)) over(partition by Id, groupordinal order by startdate) as runningtotal
    from
    (
        select *, sum(newgroupflag) over (partition by id order by startdate) as groupordinal
        from
        (
        select *, 
        case when lag(finishdate) over(partition by id order by startdate) < dateadd(day, -30, startdate) then 1 else 0 end as newgroupflag
        from @test
        ) as gfl
    ) as src
    order by ID, startdate;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多