zoukankan      html  css  js  c++  java
  • 如何取分组最大值记录

     分组最大值记录

    比如
        序号          名称       数量       
           1              A        20
           2              A        10
           1              B        20
           2              B        40
           3              B        10
           1              C        20
           2              C        40
    子查询:

    select * from 表 where (序号,名称) in (select max(序号),名称 from 表 group by 名称)

     分析函数:

    select 序号   ,       名称     ,  数量 from 
    (select    序号   ,       名称     ,  数量 
    ,row_number() over(partition by 名称 order by 序号  desc ) rn
    form tab_name )
    where rn=1


    select 序号   ,       名称     ,  数量 from 
    (select    序号   ,       名称     ,  数量 
    , max(序号) over(partition by 名称) rn
    form tab_name )

    where rn=序号

    注意:max的字段只能是number类型字段,如果是date类型的,会提示错误。date类型用上面的row_number()来做就可以了。


    Oracle 分组 取第一条记录
    id        apply_id
    1         1
    2         1
    3         1
    4         2
    5         2
    6         3
    7         3
    8         3

    取出
    id        apply_id
    3         1
    5         2
    8         3

    select alx_a.id
    from 
    (select id,apply_id,rownum rid from 表) alx_a,
    (select id,apply_id,rownum rid from 表) alx_b
    where alx_a.apply_id = alx_b.apply_id and alx_a.id <= alx_b.id 
    group by alx_a.id,alx_a.apply_id
    having count(*) = 1

    在oracle中有一数据表exam_result(成绩记录表),

    表中的一条记录描述了“某个班某个学生某次考试的成绩"

    create table EXAM_RESULT 

      ID      NUMBER(10) not null,                   --主键
      CLASSID NUMBER(10) not null,           --  班级id,关联到班级表
      USERID  NUMBER(10) not null,             --用户id,关联到用户表
      EXAMID  NUMBER(10) not null,             --试卷id,关联到试卷表
      RESULT  NUMBER(3)                              --成绩
    )

     

    现在要求统计完成了试卷id为1,2,3的成绩的前3名

    即完成了试卷id为1的前3名,完成了试卷id为2的前3名,完成了试卷id为3的前3名

    select * from (
          select
            e.classid,
            e.userid,
            e.examid,
            e.result,
                row_number() over (partition by e.examid order by e.examid, e.result desc) rn
                       from exam_result e
                            where e.examid in (1,2,3)
    ) where rn <= 3
     

             

                成长

           /      |     \

        学习   总结   分享

    QQ交流群:122230156

  • 相关阅读:
    cisco telnet(转载)
    华为bfd配置步骤
    cisco ssh实验--附带配置脚本-2019.11.19
    远程设备管理opendx平台搭建-server,agent以及front实际搭建
    远程设备管理opendx平台搭建-appium和adb的安装
    华为交换机sflow配置
    华为交换机netstream配置
    centos6虚拟机复制后修改网卡
    docker基本操作
    esxi 6 添加硬盘、网卡
  • 原文地址:https://www.cnblogs.com/benio/p/2202022.html
Copyright © 2011-2022 走看看