首页 > 解决方案 > 如何仅使用开始日期在两个日期之间选择数据?

问题描述

如果只有 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

标签: postgresql

解决方案


您可以通过查看下一行的开始日期来获取结束日期。这是用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');

示范


推荐阅读