如何将周末和假日的值添加到上一个工作日

时间:2018-11-14 06:55:30

标签: sql sql-server-2012

我必须将周末和节假日的值添加到上一个工作日的值,以便周末和节假日的值不应该显示在报告中,但是如果我们没有以前的工作日,则只需将行跳过为2018-01-01跳过以下输出

**DAYS      VALUE** 
2018-01-01  10  Holiday-1
2018-01-02  20  
2018-01-03  30  
2018-01-04  40  
2018-01-05  50  
2018-01-06  60  Saturday
2018-01-07  70  Sunday
2018-01-08  80  
2018-01-09  90  
2018-01-10  100 Holiday-2

输出

2018-01-02  20  
2018-01-03  30  
2018-01-04  40  
2018-01-05  180 
2018-01-08  80  
2018-01-09  190 

我正在尝试LEAD, LAG, DATEDIFF和其他方式,但没有得到任何解决方案,因此请大家帮助他解决这个问题。

2 个答案:

答案 0 :(得分:1)

如果“假期”日历表中有一行(我会假设也有周末),则需要找到当前日期之前的最大日期,“假期”表中没有该日期。然后按此“实际日期”分组并求和。像这样:

declare @t table([DAYS] date, [VALUE] int)
declare @Holidays table([DAYS] date, Note varchar(100))

insert into @t values
('2018-01-01',  10),
('2018-01-02',  20),
('2018-01-03',  30),
('2018-01-04',  40),
('2018-01-05',  50),
('2018-01-06',  60),
('2018-01-07',  70),
('2018-01-08',  80),
('2018-01-09',  90),
('2018-01-10',  100)

insert into @Holidays values
('2018-01-01',  'Holiday-1'),
('2018-01-06',  'Saturday'),
('2018-01-07',  'Sunday'),
('2018-01-10',  'Holiday-2')

;with cte as (
select 
    IIF(h1.[DAYS] is not null /* i.e. it is a holiday */,
         (select max([DAYS])
          from @t t2
          where t2.[DAYS] < t1.[DAYS] and not exists(select * from @Holidays h2 where h2.[DAYS] = t2.[DAYS])), t1.[DAYS]) as RealDate
    , t1.[VALUE]
from @t t1
left join @Holidays h1 on t1.DAYS = h1.[DAYS]
)
select
    RealDate
    , sum([VALUE]) as RealValue
from cte
where RealDate is not null
group by RealDate

答案 1 :(得分:0)

您可以使用累计和(定义组)和汇总来执行此操作。将组定义为给定日期或之前的非节假日数,然后进行汇总。对于非节假日和假期,这是相同的值。

然后合计:

select max(days) as days, sum(value)
from (select t.*,
             sum(case when holiday is null then 1 else 0 end) over (order by days asc) as grp
      from t
     ) t
group by grp;

编辑:

使用单独的假期表,您只需添加join

select max(days) as days, sum(value)
from (select t.*,
             sum(case when h.holiday is null then 1 else 0 end) over (order by t.days asc) as grp
      from t left join
           holidays h
           on t.days = h.date
     ) t
group by grp;