上个月开始和结束的 Postgres epoch 提取

Postgres epoch extract begining and end of last month

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

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};

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

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

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

如果避免使用 between 运算符,则不需要计算上个月的 "last second",只需计算当月的开始:

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));

请注意 < 运算符而不是 <=