【问题标题】:Finding all rows that have a date in the current season in PostgreSQL在 PostgreSQL 中查找具有当前季节日期的所有行
【发布时间】:2021-06-17 01:25:24
【问题描述】:

我在 PostgreSQL 中有一个调查表。我想查找自本赛季开始以来所做的所有调查。 我是这样写的:

WITH foo 
AS (

SELECT 
-- This case will find the date of the first day of this season
-- Year is selected based on the current date. This way we can use the same code next year.
-- ** finding the start of the season.
CASE 
    WHEN EXTRACT('month' FROM NOW()) >= 1 AND EXTRACT('month' FROM NOW()) < 4 
        THEN TO_TIMESTAMP( EXTRACT('year' FROM NOW())||'-01-01 01:00:00', 'YYYY-MM-DD HH:MI:SS')

    WHEN EXTRACT('month' FROM NOW()) >= 4 AND EXTRACT('month' FROM NOW()) < 7
        THEN TO_TIMESTAMP( EXTRACT('year' FROM NOW())||'-04-01 01:00:00', 'YYYY-MM-DD HH:MI:SS')

    WHEN EXTRACT('month' FROM NOW()) >= 7 AND EXTRACT('month' FROM NOW()) < 9 
        THEN TO_TIMESTAMP( EXTRACT('year' FROM NOW())||'-07-01 01:00:00', 'YYYY-MM-DD HH:MI:SS')

    WHEN EXTRACT('month' FROM NOW()) >= 10 AND EXTRACT('month' FROM NOW()) < 13 
        THEN TO_TIMESTAMP( EXTRACT('year' FROM NOW())||'-10-01 01:00:00', 'YYYY-MM-DD HH:MI:SS')

END start_season
)
SELECT *
FROM foo f,
my_table t
WHERE date_survey > start_season

此解决方案有效。但是,如果存在,我正在寻找更简单的解决方案。

【问题讨论】:

    标签: sql postgresql date datetime


    【解决方案1】:

    只考虑date_trunc()

    SELECT date_trunc('quarter', date_survey) AS start_timestamp
         , *
    FROM   my_table t
    WHERE  date_survey >= date_trunc('quarter', now());
    

    值得注意的是,两个表达式产生相同的结果(可能除了数据类型),而 WHERE 子句已经到位。

    date_trunc('quarter', date_survey)
    date_trunc('quarter', now())
    

    但您可能希望对全年或其他时间使用相同的查询。然后添加的date_trunc('quarter', date_survey) 是有意义的不同:

    ...
    WHERE  date_survey >= date_trunc('year', now());
    

    或者可以添加EXTRACT('quarter' FROM date_survey) AS start_season 来添加季度号。

    注意类型为timestamp(或date)的极端情况陷阱,具体取决于当前时区设置(而不是timestamptz)。

    见:

    【讨论】:

      猜你喜欢
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 2022-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多