【问题标题】:SQL to get all data for the last 30 days from a PostgreSQL database [duplicate]SQL从PostgreSQL数据库中获取过去30天的所有数据[重复]
【发布时间】:2017-10-31 11:35:00
【问题描述】:

如何编写 SQL 以获取指定表中过去 30 天的所有数据,而无需手动指定日期?我有一张如下表:

school
(
  school_id bigint,school_name character varying(100),
  school_code character varying(10),
  created_time timestamp with time zone,
)

我正在尝试获取过去 30 天内 created_time 的所有记录。 我正在尝试类似以下的方法,但它对我不起作用:

select * from school where created_time > '2017-09-31 11:12:57.425+00';

另外,我不想手动指定日期,我想通过自动获取当前日期来获取过去 30 天的数据。有什么方法可以实现吗?

我得到的当前错误如下:

ERROR:  date/time field value out of range: "2017-09-31 11:12:57.425+00"
LINE 1: select * from school where created_time > '2017-09-31...
                                                         ^
********** Error **********

ERROR: date/time field value out of range: "2017-09-31 11:12:57.425+00"
SQL state: 22008
Character: 50

【问题讨论】:

    标签: sql postgresql timestamp


    【解决方案1】:

    只需使用current_timestamp(记录在here):

    select *
    from school
    where created_time > current_timestamp - interval '30 day';
    

    【讨论】:

    • 这对我有用,谢谢,我正在尝试从另一个表中提取更多日期,如下所示:select s.school_name, s.user_created, u.email, u.first_name from school s, ugrp_user u where subscription_term = 'trial' and s.user_created = u.user_id and created_time > current_timestamp - interval '30 day';但这给了我一个错误:错误:列引用“created_time”不明确。不知道是什么问题
    • 首先,从不from 子句中使用逗号。始终使用正确、明确的 join 语法。其次,新问题应该作为新问题提出,而不是作为 cmets 提出。第三,当查询中有多个表引用时,始终限定列名。
    • @thanks Gordon Linoff,让我试着弄清楚
    猜你喜欢
    • 2022-01-09
    • 2017-07-06
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2020-01-28
    • 2013-05-19
    相关资源
    最近更新 更多