Teradata 将多条记录合并为一条记录

Teradata merge multiple records into single record

我想将多条记录合并为一条记录 前任: 输入

pdt status start_dt end_dt
a Inactive 2022/02/02 2022/02/04
a Inctive 2022/02/05 2022/02/10
a Active 2022/02/10 2022/02/12
b Active 2022/03/13 2022/03/17

输出

pdt status start_dt end_dt
a Active 2022/02/02 2022/02/12
b Active 2022/03/13 2022/03/17

假设 start_dt 和 end_dt 都是 DATE 类型:

select pdt, status, min(start_dt), max(end_dt) from your_table
where to_char(start_dt,'YYYY/MM')=to_char(end_dt,'YYYY/MM')
group by pdt, status, to_char(start_dt,'YYYY/MM')

首先规范化日期范围,然后返回获取最新状态。

SELECT t1.pdt, t2.status, BEGIN(t1.pd) as start_dt, PRIOR(END(t1.pd)) AS end_dt
FROM (
  SELECT NORMALIZE pdt, PERIOD(start_dt, NEXT(end_dt)) pd 
  FROM mytable ) as t1
JOIN mytable t2
ON t1.pdt = t2.pdt AND PRIOR(END(t1.pd)) = t2.end_dt;