【问题标题】:Filter timestamp by specific month-year按特定月份-年份过滤时间戳
【发布时间】:2017-03-12 18:52:09
【问题描述】:

我是 postgres 的新手,如果有任何建议,我将不胜感激。我有一个带有 timestamp 列的 postgres 表,其值的格式为:1970-01-01 00:00:00

我的目标是选择过去三个月的记录 - 2016 年 12 月、2017 年 1 月和 2017 年 2 月。如何使用 SELECT 编写这个只有读取访问权限的查询?

当我开始时:

SELECT to_char("start_time", 'YYYY-MM-DD HH:MM:SS') FROM trips;

时间转换为上午/下午,但我只对按月和年提取和子集感兴趣

【问题讨论】:

    标签: sql postgresql timestamp


    【解决方案1】:

    给你:

    SELECT *
    FROM trips
    WHERE start_time BETWEEN '2016-01-01 00:00:00'::timestamp AND '2017-02-28 23:59:59'::timestamp;
    

    【讨论】:

      【解决方案2】:

      您可以使用extract 或date_trunc 函数在postgresql 中提取月份。

      非常类似于问题get last three month records from table

      有关 postgresql 中日期时间函数的更多详细信息,请使用以下链接。

      https://www.postgresql.org/docs/9.1/static/functions-datetime.html

      【讨论】:

        【解决方案3】:

        这是一种方法:

        select t.*
        from t
        where start_date >= date_trunc('month',now() - interval '3' month) and
              start_date < date_trunc('month', now());
        

        【讨论】:

        • 我收到此错误:ERROR: column "month" does not exist LINE 4: start_time &lt;- date_trunc(month, now()); 我的表中没有月份列,只有 start_date
        • @the_darkside 在我认为可行的情况下使用start_date &gt;= date_trunc('month',now()-interval '3' month) and start_date &lt; date_trunc('month', now());
        猜你喜欢
        • 1970-01-01
        • 2021-08-31
        • 1970-01-01
        • 2017-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-31
        • 2018-06-20
        相关资源
        最近更新 更多