SQL SERVER - 加入 Calendar Table 以获得周末,从周五到周六和周日带来价值
SQL SERVER - Join with Calendar Table to get Weekend, bring value from Friday to Saturday and Sunday
我正在尝试将周六和周日纳入当前结果,并将周五的值带入周六和周日。
我的初始数据集:
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');
我尝试使用 Full Outer Join/Cross Join/Lag/Lead 但没有成功。我想避免循环,我认为这不需要循环。
我也在 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'
提前感谢您的帮助。真的很感激。谢谢!
如果我理解你的问题,我认为这会起作用:
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
我正在尝试将周六和周日纳入当前结果,并将周五的值带入周六和周日。
我的初始数据集:
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');
我尝试使用 Full Outer Join/Cross Join/Lag/Lead 但没有成功。我想避免循环,我认为这不需要循环。
我也在 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'
提前感谢您的帮助。真的很感激。谢谢!
如果我理解你的问题,我认为这会起作用:
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