工作日之间的周末SQL

时间:2019-02-07 02:59:37

标签: sql plsql teradata-sql-assistant

我有一个工作日日期的列表,想要插入周末/公共假期日期的行,并在SQL中填充上一行的数据。请帮助。

See image for problem data and desired output

1 个答案:

答案 0 :(得分:0)

您的假期取决于您所在的国家/地区。这是查找星期五后插入两天的逻辑,如果您知道如何识别假期以及假期长短,也可以使用类似的逻辑。

create table #temp (fechas date, value int)



insert into #temp values ('20160601',2)
insert into #temp values ('20160602',4)
insert into #temp values ('20160603',8)
insert into #temp values ('20160606',2)
insert into #temp values ('20160607',1)


--TABLE
select *, DATEPART(DW,fechas) as dayOfTheWk 
into #temp2 
from #temp

-- selecting Fridays
declare @Fridays TABLE (fechas date,value int, dayOfTheWk int, nRow int)

insert into @Fridays
select *, DATEPART(DW,fechas) as dayOfTheWk, ROW_NUMBER() over(order by fechas) from #temp
where DATEPART(DW,fechas) = 6

declare @i int = 1, @maxI int

select @maxI = count(1) from @Fridays

while(@i <= @maxI)
begin 

        declare @x int = 1

        while (@x <= 2)
        begin 
            insert into #temp2 
            select 
                DATEADD(day,@x,fechas) as fechas, value, DATEPART(DW,DATEADD(day,@x,fechas))
            from @Fridays
            where nRow = @i 

        select @x += 1
        end 

select @i += 1
end 


select * from #temp2

fechas     value    dayOfTheWk
2016-06-01  2        4
2016-06-02  4        5
2016-06-03  8        6
2016-06-04  8        7
2016-06-05  8        1
2016-06-06  2        2
2016-06-07  1        3