查询以查找SQL查询中上一行的更改

时间:2018-12-26 10:05:38

标签: sql oracle

我有一个per_all_Assignments_f表,其中有date_fromdate_to以及以下列结构:

PERSON_ID     DATE_FROM         DATE_TO      GRADE
---------    ------------      -----------   -----
12            01-Jan-2018      28-Feb-2018     c
12            01-Mar-2018      29-Mar-2018     a
12            30-Mar-2018      31-dec-4712     b
13            01-jan-2018      31-dec-4712     c

在上表中,我必须检索最新的成绩更改,即对于person_id '12',我必须检索两条记录行:30-mar-201831 dec 4712是最新和前一行。我可以使用什么功能?

由解决:

SELECT person_id,
       asg.grade_id,
       lag(asg.grade_id) Over (Partition By person_ID Order By start_date) as prev_ppg_line1,
       lag(start_date) Over (Partition By person_ID Order By start_date) 
                                                            as prev_ppg_effective_start_date,
       start_date,
       row_Number() Over (Partition By person_ID Order By effective_start_date) as rn
  FROM asg_table asg
 WHERE person_id = 12;

此查询将获取3行,其中包含所有先前的更改。我只想在不使用有效开始日期的最大值的情况下获取最新更改

2 个答案:

答案 0 :(得分:3)

您可以在子查询中同时使用row_numberlead分析函数:

select person_id, date_From, date_to, grade
  from
  (
    with per_all_Assignments_f(person_id, date_From, date_to, grade) as
    (
     select 12,date'2018-01-01',date'2018-02-28','c' from dual union all
     select 12,date'2018-03-01',date'2018-03-29','a' from dual union all
     select 12,date'2018-03-30',date'4172-12-31','b' from dual union all
     select 13,date'2018-01-01',date'4172-12-31','c' from dual  
    )
    select t.*,
           lead(grade) over (order by date_From desc) as ld,
           row_number() over (order by date_From desc) as rn 
      from per_all_Assignments_f t
  )   
  where rn <= 2
    and grade != ld
  order by rn desc;

 PERSON_ID  DATE_FROM    DATE_TO    GRADE
 ---------- ----------- ---------- -------
     12     01.03.2018  29.03.2018    a
     12     30.03.2018  31.12.4172    b

Rextester Demo

答案 1 :(得分:1)

似乎您只希望row_number()的1或2由人划分并按开头的降序排列。

SELECT person_id,
       date_from,
       date_to,
       grade
       FROM (SELECT person_id,
                    date_from,
                    date_to,
                    grade,
                    row_number() OVER (PARTITION BY person_id
                                       ORDER BY date_from DESC) rn
                    FROM per_all_assignments_f t) x
       WHERE rn IN (1, 2)
       ORDER BY person_id ASC,
                date_from DESC;