zoukankan      html  css  js  c++  java
  • oracle按某个字段分组然后从每组取出最大的一条纪录

    需求:查询各个设备存在未消缺的缺陷,取缺陷等级最高的,作为这个设备当前的缺陷等级:
    数据源:
      
    select t.device_id, t.defect_level
      from sp_pd_defect t
     where t.deal_result <> 2
       and t.device_id in ('03060000083602',
                           '03060000085322',
                           '03060000085762',
                           '03060000087242',
                           '03060003731354')
     group by t.device_id, t.defect_level
     order by t.device_id, t.defect_level asc;

    如图:

     
     
    要求: 需求获取红色部分的内容,,那么对应的SQL语句为
     
    select device_id 设备ID, defect_level 缺陷等级 --缺陷等级,1紧急,2重大,3一般,4其他
      from (select t.device_id,
                   t.defect_level,
                   row_number() over(partition by t.device_id order by t.defect_level asc) rn
              from sp_pd_defect t
             where t.deal_result <> 2
               and t.device_id in ('03060000083602',
                                   '03060000085322',
                                   '03060000085762',
                                   '03060000087242',
                                   '03060003731354'))
     where rn = 1;

     结果如图:

     
    其中: row_number() over( partition by 分组字段 order by 排序字段 desc
  • 相关阅读:
    POJ 1141 括号匹配 DP
    881. Boats to Save People
    870. Advantage Shuffle
    874. Walking Robot Simulation
    文件操作
    861. Score After Flipping Matrix
    860. Lemonade Change
    842. Split Array into Fibonacci Sequence
    765. Couples Holding Hands
    763. Partition Labels
  • 原文地址:https://www.cnblogs.com/ryanchancrj/p/6437288.html
Copyright © 2011-2022 走看看