如何使用 Lag 比较旧行和上一行并仅在 sql 中获取更改的数据

How to compare old and previous row and get changed data only in sql using Lag

我有一个 table xx_asg 结构:

person_id  grade_id effective_start_date effective_end_date
1            null       28-Jan-97             28-Jan-16
1            35         29-Jan-16             31-Dec-4712
6            35         12-Jun-93             31-Jul-93
6            35         01-Aug-93             30-Sep-99

我必须通过比较上一行和下一行来找出 grade_id 是否有任何变化。 如果有变化,那么我必须获取带有标志 'Y' 的新列 还有新年级的effective_start_date。我尝试创建以下查询:

SELECT  *
From    (
        Select  Person_id,
   Grade_Id,
                LAG(grade_id) OVER (PARTITION BY person_ID ORDER BY effective_start_Date) AS prev_grade_line1,
                Row_Number() Over (Partition By Person_Id Order By Effective_Start_Date Desc) As Rn,
                Effective_Start_Date
                        From    xx_asg
  --WHERE   person_ID = 3
        )
Where   Rn = 1
order by person_id

;

但此查询也返回 prev_grade_line1 和新的成绩 ID 为空或相同:

Output should look like :

person_id  grade_id prev_grade_id effective_start_date Flag
1            null       35             29-Jan-97        Y         
6            35         35             NULL             NULL


OR 

ONLY CHAGED ROW 
person_id  grade_id prev_grade_id effective_start_date Flag
1            null       35             29-Jan-97        Y    

使用时:

此查询也返回第一行。那就是将第一行的前一个 ggrade 视为 null。实际上只有 3 个更改,但此查询返回四个更改

使用 where 条件在获取上一行的值后仅获取所需的行。

select t.*, 'Y' flag
from (
select  
Person_id,
Grade_Id,
LAG(grade_id) OVER(PARTITION BY person_ID ORDER BY effective_start_Date) prev_grade_line1,
Effective_Start_Date,
row_Number() Over(Partition By Person_Id Order By Effective_Start_Date) As rn
from xx_asg
) t
where nvl(grade_id,10000000) <> nvl(prev_grade_line1,10000000) 
and rn > 1