当两列具有相同的值时如何获取最后一条记录?
how to get the last record when two columns have same values?
我想在 gr_number 和课程
的基础上获得基于 Updated_ts 的最后一行
我正在使用以下查询。
select t.*
from (select st.gr_number,st.course,st.is_active_flg,st.status,st.updated_ts
,sum(case when st.status = 'COMPLETED' then 1 else 0 end) over (partition by st.gr_number) as completedCourse,
sum(case when st.status <> 'COMPLETED' and st.status <> 'APPLICATION' and st.is_active_flg = 'N' then 1 else 0 end) over (partition by st.gr_number) as IncompletCourse
from admission_log st
join course cr on cr.course_id=st.course
order by st.gr_number,st.course,st.updated_ts
) t
where completedCourse > 0 and IncompletCourse > 0;
这个查询给我的结果是
从上面的结果我只想要最后一个值与相同的 gr_number 和基于 Updated_ts
的课程
喜欢
请帮忙
我想你可以使用 row_number()
:
select t.*
from (select st.gr_number, st.course, st.is_active_flg, st.status, st.updated_ts,
sum(case when st.status = 'COMPLETED'
then 1 else 0
end) over (partition by st.gr_number) as completedCourse,
sum(case when st.status <> 'COMPLETED' and st.status <> 'APPLICATION' and st.is_active_flg = 'N'
then 1 else 0
end) over (partition by st.gr_number) as IncompletCourse,
row_number() over (partition by st.gr_number order by updated_ts desc) as seqnum
from admission_log st join
course cr
on cr.course_id = st.course
) t
where completedCourse > 0 and IncompletCourse > 0 and
seqnum = 1;
我认为不需要您的 where
过滤器,但我已将它们留在里面。
我想在 gr_number 和课程
的基础上获得基于 Updated_ts 的最后一行我正在使用以下查询。
select t.*
from (select st.gr_number,st.course,st.is_active_flg,st.status,st.updated_ts
,sum(case when st.status = 'COMPLETED' then 1 else 0 end) over (partition by st.gr_number) as completedCourse,
sum(case when st.status <> 'COMPLETED' and st.status <> 'APPLICATION' and st.is_active_flg = 'N' then 1 else 0 end) over (partition by st.gr_number) as IncompletCourse
from admission_log st
join course cr on cr.course_id=st.course
order by st.gr_number,st.course,st.updated_ts
) t
where completedCourse > 0 and IncompletCourse > 0;
这个查询给我的结果是
从上面的结果我只想要最后一个值与相同的 gr_number 和基于 Updated_ts
的课程喜欢
请帮忙
我想你可以使用 row_number()
:
select t.*
from (select st.gr_number, st.course, st.is_active_flg, st.status, st.updated_ts,
sum(case when st.status = 'COMPLETED'
then 1 else 0
end) over (partition by st.gr_number) as completedCourse,
sum(case when st.status <> 'COMPLETED' and st.status <> 'APPLICATION' and st.is_active_flg = 'N'
then 1 else 0
end) over (partition by st.gr_number) as IncompletCourse,
row_number() over (partition by st.gr_number order by updated_ts desc) as seqnum
from admission_log st join
course cr
on cr.course_id = st.course
) t
where completedCourse > 0 and IncompletCourse > 0 and
seqnum = 1;
我认为不需要您的 where
过滤器,但我已将它们留在里面。