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
  • 相关阅读:
    2009年信息技术十大趋势
    转:ASP.NET MVC 第五个预览版和表单提交场景
    终于在博客园开通了
    与虚拟机Oracle连接出现ora12154问题的解决
    Frame框架页面加载中进度条的实现
    WordPress安装部署
    Xmarks不会关闭了,太好了!
    抠出淘宝的菜单树
    asp.net实现类似MaskTextBox功能
    win2003 64位系统下ODBC连接使用
  • 原文地址:https://www.cnblogs.com/moonwind/p/4561458.html
Copyright © 2011-2022 走看看