我有下表
ID Date Indicator
12345 1/1/2001 N
12345 2/1/2001 N
12345 3/1/2001 N
12345 4/1/2001 Y
12345 5/1/2001 Y
12345 6/1/2001 Y
67891 2/1/2002 N
67891 3/1/2002 N
67891 4/1/2002 Y
67891 5/1/2002 Y
67891 6/1/2002 Y
我想拉出指标更改的第一行,例如
ID Date Indicator
12345 1/1/2001 N
12345 4/1/2001 Y
67891 2/1/2002 N
67891 4/1/2002 Y
并且只有指标发生变化的第二行
ID Date Indicator
12345 4/1/2001 Y
67891 4/1/2002 Y
答案 0 :(得分:1)
使用分析功能的三步解决方案如下所示。 我假设你的桌子是TEST
-- add IS_CHANG E= 'Y' for change in Indicator
with test1 as (
select a.*,
case when lag(indicator,1,'X') over (partition by ID order by date_d) != indicator then 'Y' end as is_change
from test a),
-- filter changes only and numerate records
test2 as (
select a.*,
row_number() over (partition by id order by date_d) as RN
from test1 a
where is_change = 'Y')
-- get only 2nd change
select ID, DATE_D, INDICATOR from test2
where rn = 2
;