【发布时间】:2020-11-14 14:37:46
【问题描述】:
我有以下数据:
使用下面的查询,我得到以下结果:
我想得到什么结果:
如何修改我的查询以获取最后一个表?
with minmax as (select t1.*,
case when rank=(min(rank) over (partition by id)) then status end as first_status,
case when rank=(min(rank) over (partition by id)) then status_date end as first_status_date,
case when rank=(max(rank) over (partition by id)) then status end as last_status,
case when rank=(max(rank) over (partition by id)) then status_date end as last_status_date,
max(rank) over (partition by id) as max
from (select id,
status_date,
status,
rank()
over (partition by id order by id, status_date) as rank
from history_table as hist
) as t1
group by 1, 2, 3, 4
order by id, status_date)
select distinct
id,
first_status,
first_status_date,
last_status,
last_status_date
from id_table as idt
left join minmax as mm on idt.id=mm.id
【问题讨论】:
标签: sql postgresql date pivot window-functions