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
  • 相关阅读:
    75. Sort Colors
    101. Symmetric Tree
    121. Best Time to Buy and Sell Stock
    136. Single Number
    104. Maximum Depth of Binary Tree
    70. Climbing Stairs
    64. Minimum Path Sum
    62. Unique Paths
    css知识点3
    css知识点2
  • 原文地址:https://www.cnblogs.com/ryanchancrj/p/6437288.html
Copyright © 2011-2022 走看看