【问题标题】:How to Select Between Two Specific Date Ranges如何在两个特定日期范围之间进行选择
【发布时间】:2021-12-14 12:50:16
【问题描述】:

假设我想要一个特定的时间间隔,例如 (mm/dd/yyyy-1 - 1/1/yyyy-1)

如何在 postgres 中查询这个?

到目前为止,我已经解决了以下问题:

SELECT * 
FROM my_table 
WHERE date BETWEEN (now()::DATE - INTERVAL '1 year') - ‘1/1/?’ AND (now() - INTERVAL '1 year') - ‘1/1/?’

我不太确定如何获得前一年。

我在正确的轨道上吗?对不起,我是新手。谢谢!

【问题讨论】:

    标签: sql postgresql date between


    【解决方案1】:

    如果你愿意,你可以使用这样的东西:

    select * from table 
     where data between to_date(concat('01/01/', EXTRACT (YEAR FROM now()) - 1), 'mm/dd/yyyy') and (now()::DATE - interval '1 year')
    

    但是用的比较多的是date_trunc

    select * from table
    where date >= date_trunc('year', now()::DATE - interval '1 year')
      and date  < date_trunc('year', now()::DATE)
    

    当您使用date_trunc('year', now()::DATE) 时,日期为 01,月份为 01,年份为今年。

    【讨论】:

      【解决方案2】:

      您可以使用date_trunc()获取年初:

      select *
      from my_table
      where date >= date_trunc('year', current_date - interval '1 year')
        and date  < date_trunc('year', current_date)
      

      date_trunc('year', current_date) 返回今年年的第一天。由于我使用&lt; 作为上限,这将包括上一年 12 月 31 日之前的所有日期。

      如果您确实想使用BETWEEN(只有在date 定义为date 数据类型时才能正常工作),那么您可以使用:

      select *
      from my_table
      where date between date_trunc('year', current_date - interval '1 year')::date
                     and date_trunc('year', current_date)::date - 1
      

      请注意,上限已转换为 date,然后我减去 1 天以在 12 月 31 日登陆。这是必要的,因为between 包含这两个值。

      【讨论】:

      • 您好,感谢您的回复!但是有没有办法改写查询以使用 BETWEEN... AND..?是否有理由使用 date_trunc 而不是说 "now()::DATE - INTERVAL '1 year'" 来获得 mm/dd/yyyy-1 ?
      • 如果您正在处理时间戳,基本上总是使用&gt;= ... AND &lt; 而不是BETWEEN 更好。但如果你真的想在之间使用,请参阅我的编辑
      猜你喜欢
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多