首页 > 解决方案 > SQL SERVER - 加入日历表以获得周末,从周五到周六和周日带来价值

问题描述

我试图将周六和周日纳入当前结果,并将周五的值带到周六和周日。

我的初始数据集:

create table AA as (userid varchar(10), return_date datetime,  first_date  
datetime);
insert into AA 
select ('A',  '2019-06-07', '2019-06-01 15:46:43.000')
union all 
select ('A',  '2019-06-10', '2019-06-01 15:46:43.000')
union all 
select ('B',  '2019-06-07', '2019-06-03 15:46:43.000')
union all 
select ('B',  '2019-06-10', '2019-06-03 15:46:43.000');

我曾尝试使用完全外连接/交叉连接/滞后/领先,但没有成功。我想避免循环,我认为这不需要循环。

此外,由于我在 Azure SQL DataWarehouse 上工作,因此存在许多限制,例如递归 cte 是有限的。

这是我正在寻找的结果:

userid,     return_date,        first_date
A,          '2019-06-07',       '2019-06-01 15:46:43.000'
A,          '2019-06-08',       '2019-06-01 15:46:43.000'
A,          '2019-06-09',       '2019-06-01 15:46:43.000'
A,          '2019-06-10',       '2019-06-01 15:46:43.000'
B,          '2019-06-07',       '2019-06-03 15:46:43.000'
B,          '2019-06-08',       '2019-06-03 15:46:43.000'
B,          '2019-06-09',       '2019-06-03 15:46:43.000'
B,          '2019-06-10',       '2019-06-03 15:46:43.000'

提前感谢您的帮助。真的很感激。谢谢!

标签: sql-servermissing-datawith-statementazure-sqldwazure-sql-data-warehouse

解决方案


如果我明白你在问什么,我认为这会起作用:

    select * from aa
    union
    select userid, dateadd(d,1,return_date) return_date, first_date from aa 
        where datepart(dw, return_date) = 6 -- only returns Fridays, translate to Sat
    union
    select userid, dateadd(d,2,return_date) return_date, first_date from aa 
        where datepart(dw, return_date) = 6 -- only returns Fridays, translate to Sun
    order by userid, return_date

推荐阅读