sql-server - 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'
提前感谢您的帮助。真的很感激。谢谢!
解决方案
如果我明白你在问什么,我认为这会起作用:
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
推荐阅读
- python - 如何在 numpy 中获取两个索引数组之间的矩阵元素?
- angular - 无法读取underfined的属性
- c# - 序列化 LambdaExpression 到字符串和从字符串中保存以保存在数据库中
- azure-devops - 带有模板的 azure devops yaml 管道不签出引用的存储库
- python - 在列表中查找最大值及其索引 - 不断得到错误的索引
- mongodb - GORM - 获取域类属性的原始 DB 值
- r - 如何为栅格设置正确的投影?
- excel - 从多个工作表中查找同一列的总计,并在新工作表的工作表名称旁边表示总计
- c# - 我的 Azure API(文本翻译、计算机视觉)的端点不可访问(错误代码 404)
- java - QuerySyntaxException:意外令牌:使用标准构建器在 postgresql 中的日期之间产生差异