zoukankan      html  css  js  c++  java
  • 用SQL查询方式显示GROUP BY中的TOP解决方法[转]

    用SQL查询方式显示GROUP BY中的TOP
    怎样用一个SQL语句来显示
    分组后每个组的前几位
    比如把一个学校所有学生的成绩按班级分组,再显示每个班级前五名的信息。
    班级     学生   成绩
    一班     李X       100
    一班     王X       99
    一班     刘X       98
    一班     赵X       97
    一班     孙X       96
    二班     李W       100
    二班     王W       99
    二班     刘W       98
    二班     赵W       97
    二班     孙W       96
    ......

    ------解决方案--------------------
    declare @t table (class varchar(20),name varchar(10),grade int)
    insert @t select '一班 ', '李X ',100
    union all select '一班 ', '王X ',99
    union all select '一班 ', '刘X ',98
    union all select '一班 ', '赵X ',97
    union all select '一班 ', '孙X ',96
    union all select '一班 ', '孙X ',78
    union all select '二班 ', '李W ',100
    union all select '二班 ', '王W ',99
    union all select '二班 ', '刘W ',98
    union all select '二班 ', '赵W ',97
    union all select '二班 ', '孙W ',96
    union all select '二班 ', '孙X ',88

    select * from @t a where
    (select count(1) from @t where class="a".class and grade> a.grade) <5
    order by class,grade desc
    --结果
    class name grade
    -------------------- ---------- -----------
    二班 李W 100
    二班 王W 99
    二班 刘W 98
    二班 赵W 97
    二班 孙W 96
    一班 李X 100
    一班 王X 99
    一班 刘X 98
    一班 赵X 97
    一班 孙X 96

    (所影响的行数为 10 行)

    原文地址:http://www.myexception.cn/sql-server/158915.html

  • 相关阅读:
    shell test用法
    Makefile debug的经验
    Makefile 中:= ?= += =的区别
    Makefile中常用的函数
    Makefile选项CFLAGS,LDFLAGS,LIBS
    makefile双冒号规则
    makefile中的伪目标,强制目标和双冒号规则
    makefile 使用环境变量
    linux shell if语句使用方法
    linux的test命令
  • 原文地址:https://www.cnblogs.com/zhangzt/p/3472609.html
Copyright © 2011-2022 走看看