【问题标题】:how to get the last record when two columns have same values? [duplicate]当两列具有相同的值时如何获取最后一条记录? [复制]
【发布时间】:2020-05-20 07:04:09
【问题描述】:

我想在相同 gr_number 和 course 的基础上获得基于 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;

这个查询给我的结果是

从上面的结果中,我只想要基于 Updated_ts 的相同 gr_number 和课程的最后一个值

喜欢

请帮忙

【问题讨论】:

    标签: sql oracle greatest-n-per-group


    【解决方案1】:

    我觉得你可以用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 过滤器,但我已将它们留在里面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      • 2020-07-07
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      相关资源
      最近更新 更多