我有下面表格中的数据。
cntrct_number status_cd registration_date
123 A 23-03-19
123 A 06-06-19
123 S 10-06-21
123 S 11-06-21
123 S 12-06-21
123 A 13-06-21
123 S 14-06-21
123 S 15-06-21
现在我想要status_cd = 'S'的两个最小日期类似查询应该给出如下输出:
123 S 11-06-21
123 S 14-06-21
输出是当状态改变时,它应该在状态改变后立即取第一行。
您可以使用where按状态筛选结果,然后按日期排序,最后一步将输出限制为2行:
select * from table where status_cd = 'S' order by registration_date limit 2;
我们要找的是窗口函数的限定条件。
条件1:状态码为S。条件2:前面的状态码不是s
create or replace transient table T1(cntrct_number int, status_cd string, registration_date date);
insert into T1 (cntrct_number, status_cd, registration_date) values
(123, 'A', to_date('23-03-19', 'DD-MM-YY')),
(123, 'A', to_date('06-06-19', 'DD-MM-YY')),
(123, 'S', to_date('10-06-21', 'DD-MM-YY')),
(123, 'S', to_date('11-06-21', 'DD-MM-YY')),
(123, 'S', to_date('12-06-21', 'DD-MM-YY')),
(123, 'A', to_date('13-06-21', 'DD-MM-YY')),
(123, 'S', to_date('14-06-21', 'DD-MM-YY')),
(123, 'S', to_date('15-06-21', 'DD-MM-YY'));
select cntrct_number
,status_cd
,registration_date
from T1
qualify STATUS_CD = 'S'
and lag(STATUS_CD) over (partition by cntrct_number order by registration_date) <> 'S'
;