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
  • 相关阅读:
    javascript的this
    javascript里的prototype
    【每天进步一点点 Python 】Python 字典(Dictionary) items()方法 用法
    【每天进步一点点--Python】字典dic类型 转换成 str 类型 json.dumps()
    【每天进步一点点
    【每天get 一点新知识】Python print 打印结果(字符串类型)前面添加 说明
    【每天get 到一点小知识】python 取response data 里面的数据
    【python web 开发】第三方登录开发模式及Oauth2.0 简介
    每天一个小程序:读取txt文件存储到excel 表中(2)
    每天一个小程序:读取txt文件存储到excel 表中
  • 原文地址:https://www.cnblogs.com/moonwind/p/4561458.html
Copyright © 2011-2022 走看看