我正在尝试检索包含一年中每个月的最大时间戳的记录。
为此,我从2016年1月到今天每月创建一个临时表(date_series)。我想找到一年中每个月的每个ID的最大时间戳,并显示相应的ID和状态。
这是我到目前为止所做的:
createddate
字段是
with date_series as(
SELECT * FROM generate_series('2016-01-01'::date,
now(), '1 month')
)
select max(a.created_at), a.id, d.generate_series, a.status
from sales a, date_series d
group by 2,3,4
但是我不确定如何在逻辑上构建查询以达到这些结果。
答案 0 :(得分:1)
了解 DISTINCT ON http://www.postgresqltutorial.com/postgresql-select-distinct/
试试这个
SELECT DISTINCT ON(a.id, a.status, date_trunc('month',cdate))
a.id,
a.status,
date_trunc('month',cdate) "Month",
a.created_at
FROM sales a
ORDER BY a.id, a.status, date_trunc('month',cdate), created_at DESC
答案 1 :(得分:1)
假设您的月份没有差距(或者不在乎),并且时间戳确实是唯一的,这应该有效:
with salez as (
select
id, status, created_at,
max (created_at) over (partition by date_trunc ('month', created_at)) as max_date
from
sales
)
select
max_date, id, date_trunc ('month', created_at)::date, status
from salez
where
max_date = created_at
max
的风险是,如果您有两个具有完全相同时间戳的记录,这将为您提供该月的两个输出记录。如果可能并且会破坏您的查询,请改为使用row_number
:
with salez as (
select
id, status, created_at,
row_number() over (partition by date_trunc ('month', created_at
order by id desc)) as rn
from
sales
)
select
created_at, id, date_trunc ('month', created_at)::date, status
from salez
where
rn = 1