我有一个表per_all_Assignments_f
,其中包含date_from
和date_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-2018
31 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 行。我只想获取最新更改,而不在有效开始日期使用 max
您可以在子查询中同时使用row_number
和lead
分析函数,如下所示:
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 演示
似乎您只想要所有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;