【问题标题】:Postgres epoch extract begining and end of last month上个月开始和结束的 Postgres 纪元摘录
【发布时间】:2018-07-10 11:44:34
【问题描述】:

我需要在 postgres 中查找表历史记录中的行数,其中时钟列中的日期来自上个月(时钟存储为纪元时间戳)。 首先我做了:

select count(clock) from history where 
date_trunc('month',to_timestamp(clock)) = date_trunc('month', CURRENT_DATE) - INTERVAL '1 month';

但这很慢。我在想如果我这样做会更快:

select count(clock) from history 
where clock between {extracted first second of previous month} and {extracted last second of previous month};

当我手动输入值时,速度要快得多(我有时钟索引)。但我不知道如何提取上个月的第一和最后一秒。 提前感谢您的帮助:)

【问题讨论】:

    标签: postgresql time epoch


    【解决方案1】:

    上个月的开始作为时间戳是:

    date_trunc('month', current_timestamp) - interval '1' month
    

    如果避免使用between 运算符,则不需要计算上个月的“最后一秒”,而只需计算当月的开始:

    select count(clock) 
    from history 
    where clock >= extract(epoch from date_trunc('month', current_timestamp) - interval '1' month)
      and clock < extract(epoch from date_trunc('month', current_timestamp));
    

    注意&lt; 运算符而不是&lt;=

    【讨论】:

    • 谢谢!!!!很简单,我花了 3 个小时才弄明白 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 2014-11-25
    相关资源
    最近更新 更多