Вы можете использовать группу LAG для получения значений предыдущих строк, справочных документов LAG
create table table_1(ID string,Level int,start_dt timestamp,End_dt timestamp);
insert into table_1 values
('A',1,'2018-03-12 18:39:10','2020-01-01 00:00:00'),
('A',1,'2018-01-17 13:21:26','2018-03-12 18:39:10'),
('A',2,'2018-01-14 13:21:17','2018-01-17 13:21:26');
SQL:
select id,curr_level,prev_level,
case when curr_level=prev_level then 'No Ups - Downs'
when curr_level>prev_level then 'Downgrade'
when curr_level<prev_level then 'Up-Downgrade'
when prev_level is null then 'No-Previous Level'
else 'Unkonwn state'
end upgrade_downgrade_description
from(
select table_1.id,
table_1.level as curr_level,
lag(table_1.level,1) over (partition by table_1.id order by table_1.end_dt desc) prev_level
from table_1) s;
Вывод:
id curr_level prev_level upgrade_downgrade_description
A 1 NULL No-Previous Level
A 1 1 No Ups - Downs
A 2 1 Downgrade