【问题标题】:SQL SERVER - Join with Calendar Table to get Weekend, bring value from Friday to Saturday and SundaySQL SERVER - 加入日历表以获得周末,从周五到周六和周日带来价值
【发布时间】:2019-10-25 19:20:55
【问题描述】:

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

我的初始数据集:

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 数据仓库,因此存在许多限制,例如递归 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-server missing-data with-statement azure-sqldw azure-sql-data-warehouse


    【解决方案1】:

    如果我理解您的要求,我认为这会起作用:

        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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 2019-09-07
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      相关资源
      最近更新 更多