sql - SQL如何编写返回缺失日期范围的查询?
问题描述
我试图弄清楚如何编写一个查询来查看某些记录并找到从今天到9999-12-31之间缺少的日期范围。我的数据如下所示:
ID |start_dt |end_dt |prc_or_disc_1
10412 |2018-07-17 00:00:00.000 |2018-07-20 00:00:00.000 |1050.000000
10413 |2018-07-23 00:00:00.000 |2018-07-26 00:00:00.000 |1040.000000
因此,对于这些数据,我希望我的查询返回:
2018-07-10 | 2018-07-16
2018-07-21 | 2018-07-22
2018-07-27 | 9999-12-31
我不确定从哪里开始。这可能吗?
解决方案
您可以使用 MS SQL 中的 lag() 函数来做到这一点(但从 2012 年开始可用?)。
with myData as
(
select *,
lag(end_dt,1) over (order by start_dt) as lagEnd
from myTable),
myMax as
(
select Max(end_dt) as maxDate from myTable
)
select dateadd(d,1,lagEnd) as StartDate, dateadd(d, -1, start_dt) as EndDate
from myData
where lagEnd is not null and dateadd(d,1,lagEnd) < start_dt
union all
select dateAdd(d,1,maxDate) as StartDate, cast('99991231' as Datetime) as EndDate
from myMax
where maxDate < '99991231';
如果 lag() 在 MS SQL 2008 中不可用,那么您可以使用 row_number() 和加入来模仿它。
推荐阅读
- google-cloud-platform - Google AutoML 训练错误
- android - 输入路径中的Android ffmpeg空白导致“没有这样的文件或目录”
- php - MVC没有打开链接它应该如何“控制器/动作”
- dataframe - 使用 pyspark 为动态表创建 XPATH 行
- javascript - withRouter 不会将 Route 道具传递给组件
- c# - 仅显示标题数据但不显示数据集上的详细信息数据(水晶报表 c#)
- reactjs - React-Bootstrap 在检查用户电子邮件是否经过验证时,我无法显示警报
- python - python-rq Queue.job_ids 总是空的
- javascript - 无法在浏览器上访问 Docker nodejs 容器
- c# - 如何使用来自asp.net中子gridview的路径从服务器下载文件