【问题标题】:query date ranges postgresql查询日期范围 postgresql
【发布时间】:2018-01-24 13:19:51
【问题描述】:

我有以下 postgresql 表;

ID  Date
 1  [2017-01-01,2051-01-01)
 2  [2017-01-01,2051-01-01)
 3  [2017-01-01,2051-01-01)
 4  [2017-01-01,2051-01-01)
 5  [2000-01-01,2017-01-01)
 6  [2000-01-01,2017-01-01)
 7  [2017-01-01,2051-01-01)
 8  [2017-01-01,2051-01-01)
 9  [2017-01-01,2051-01-01)
 10 [2017-01-01,2051-01-01)

如何在日期范围内进行查询,以便 2003 年 6 月返回 ID 5 和 6。

【问题讨论】:

    标签: sql postgresql date date-range


    【解决方案1】:

    使用遏制运算符<@

    with my_table(id, dates) as (
    values
        (1, '[2017-01-01,2051-01-01)'::daterange),
        (2, '[2017-01-01,2051-01-01)'),
        (3, '[2017-01-01,2051-01-01)'),
        (4, '[2017-01-01,2051-01-01)'),
        (5, '[2000-01-01,2017-01-01)'),
        (6, '[2000-01-01,2017-01-01)'),
        (7, '[2017-01-01,2051-01-01)'),
        (8, '[2017-01-01,2051-01-01)'),
        (9, '[2017-01-01,2051-01-01)'),
        (10, '[2017-01-01,2051-01-01)')
    )
    
    select *
    from my_table
    where '2003-06-01'::date <@ dates;
    
     id |          dates          
    ----+-------------------------
      5 | [2000-01-01,2017-01-01)
      6 | [2000-01-01,2017-01-01)
    (2 rows)    
    

    阅读Range Functions and Operators.


    您还可以检查dates:是否包含日期范围(不是单个日期)

    where daterange('2003-01-01', '2003-12-31') <@ dates;
    

    或者日期范围是否重叠dates:

    where daterange('2003-01-01', '2003-12-31') && dates;
    

    【讨论】:

    • 如果我们只修改为 2003 年,没有月份,查询将如何变化。
    【解决方案2】:

    https://www.postgresql.org/docs/current/static/functions-range.html

    使用包含运算符,例如:

    postgres=# select '[2000-01-01,2017-01-01)'::daterange @> '2013.01.01'::date;
     ?column?
    ----------
     t
    (1 row)
    

    所以对你来说就像

    select * from tbl where "Date" @> '2013.01.01'::date;
    

    【讨论】:

      猜你喜欢
      • 2014-06-13
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 2019-08-16
      相关资源
      最近更新 更多