sql - 在日期范围之间分配天数
问题描述
我有一张这样的桌子:
LeaveRequestID | DateAllocated | DateFrom | DateTo | TotalLeaveDays
1 | 2020-03-02 | 2020-03-02 | 2020-03-05 | 3
2 | 2020-03-02 | 2020-03-02 | 2020-03-04 | 2
这是我的查询:
SELECT
t1.DateAllocated,
t2.DateFrom,
t2.DateTo,
DATEDIFF(DAY, t2.DateFrom, t2.DateTo) TotalLeaveDays
FROM
tblLeave_Allocation t1
INNER JOIN
tblLeave_Requests t2 ON CONVERT(VARCHAR, t1.DateAllocated, 23) = CONVERT(VARCHAR, t2.DateFrom, 23)
这是我想要的输出:
LeaveRequestID | DateAllocated | DateFrom | DateTo | TotalLeaveDays | DateDist | LeaveCount
1 | 2020-03-02 | 2020-03-02 | 2020-03-05 | 3 | 2020-03-03 | 1
1 | 2020-03-02 | 2020-03-02 | 2020-03-05 | 3 | 2020-03-04 | 1
1 | 2020-03-02 | 2020-03-02 | 2020-03-05 | 3 | 2020-03-05 | 1
2 | 2020-03-02 | 2020-03-02 | 2020-03-04 | 2 | 2020-03-03 | 1
2 | 2020-03-02 | 2020-03-02 | 2020-03-04 | 2 | 2020-03-04 | 1
我想TotalLeaveDays
从后天开始为每个计数DateFrom
分配每个单曲计数DateTo
。如何达到我想要的输出?
解决方案
递归 CTE 似乎很适合这个:
with cte as (
select LeaveRequestID, DateAllocated, DateFrom, DateTo, TotalLeaveDays,
1 as n, dateadd(day, 1, datefrom) as datedist
from t
union all
select LeaveRequestID, DateAllocated, DateFrom, DateTo, TotalLeaveDays,
n + 1, dateadd(day, 1, datedist) as datedist
from cte
where n < TotalLeaveDays
)
select LeaveRequestID, DateAllocated, DateFrom, DateTo, TotalLeaveDays, datedist, 1
from cte;
推荐阅读
- python - Python通过水平虚线将图像拆分为多个部分
- r - 为什么我得到向上的生存曲线(累积发病率)?
- java - 如何从 Json 中坚持 @OneToMany 和 @ManyToOne
- javascript - 如何在类组件中使用 useMediaQuery
- r - 在 R 中,如何更改行和列的位置?
- html - 在 Div 之间绘制连接线?
- c - 如何正确初始化 sigset_t
- google-cloud-platform - Apache Beam File IO - 监视文件修改
- vue.js - 对使用的 API 数据进行排序时出现问题
- .net - 使用 .Net 框架实现分层架构的 Serilog