postgresql - 如何仅使用开始日期在两个日期之间选择数据?
问题描述
如果只有 start_date 可用,我在两个日期之间选择数据时遇到问题。
我想查看的示例是 discount_nr 在 2020 年 7 月 1 日和 2020 年 7 月 15 日之间或仅在 2020 年 7 月 14 日之间活跃的一天。我尝试了不同的解决方案、日期范围、生成系列等,但仍然无法使其正常工作。
表只有开始日期,没有结束日期
例子:
discount_nr, start_date
1, 2020-06-30
2, 2020-07-03
3, 2020-07-10
4, 2020-07-15
解决方案
您可以通过查看下一行的开始日期来获取结束日期。这是用lead
. lead(start_date) over(order by start_date asc)
将为您提供下一行的 start_date。如果我们需要 1 天的时间,我们将获得包含的结束日期。
与单独的开始/结束列相比,单个日期范围列更易于使用。您可以将其用作 CTE 或创建视图。
create view discount_durations as
select
id,
daterange(
start_date,
lead(start_date) over(order by start_date asc)
) as duration
from discounts
现在查询很容易使用范围运算符。@>
检查范围是否包含日期。
select *
from discount_durations
where duration @> '2020-07-14'::date
并用于&&
查看它们是否有任何重叠。
select *
from discount_durations
where duration && daterange('2020-07-01', '2020-07-15');
推荐阅读
- c++ - Visual Studio 2019 不想为 LIB 版本生成 ASM 文件,我做错了什么?
- netsuite - 根据模板的 NetSuite 自定义字段
- javascript - 对象中的箭头函数和简单函数行为
- javascript - 正则表达式删除数字以外的字符并仅在 Angular 6 中允许单个小数点
- django - django模型多个主键
- java - 如果元素是动态的,则无法定位元素
- reactjs - 使用返回对象内的对象的高阶组件的 mapState 函数遇到编译错误
- android - 如何在点击时设置计时器?
- flutter - Flutter:未能将本地化与 Provider 包结合起来
- opencv - 使用 OpenCV 检测图像是否有故障