如何按状态流转顺序更新日期列?SQL行转列缺省值调整需求
修改后的查询语句
select NUMBER_ID, deadline_date, (array_agg(STATUS) within group(order by updated_at_datetime desc)[0])::varchar as last_status, -- 调整clicked_date的优先级取值逻辑 coalesce( max(case when STATUS = 'clicked' THEN updated_at_datetime END), max(case when STATUS = 'claimed' THEN updated_at_datetime END), max(case when STATUS = 'bought' THEN updated_at_datetime END), '2999-12-31'::datetime ) as clicked_date, coalesce(max(case when STATUS = 'claimed' THEN updated_at_datetime END),'2999-12-31'::datetime) as claimed_date, coalesce(max(case when STATUS = 'bought' THEN updated_at_datetime END),'2999-12-31'::datetime) as bought_date from TBL_A a group by 1,2 order by number_id
调整说明
仅修改了clicked_date字段的coalesce参数顺序,按需求实现优先级取值:
- 优先取当前
number_id下CLICKED状态的更新时间 - 不存在CLICKED记录则取同ID下CLAIMED状态的更新时间
- 也不存在CLAIMED记录则取同ID下BOUGHT状态的更新时间
- 最终兜底值保留
2999-12-31(实际不会触发,因为参与分组的ID至少存在一条状态记录)claimed_date和bought_date的逻辑完全保留原有规则,不存在时仍默认赋值为2999-12-31。
内容的提问来源于stack exchange,提问作者user3461502
相关产品推荐
相关产品推荐

