zoukankan      html  css  js  c++  java
  • sqlserver巧用row_number和partition by分组取top数据

    目录

    复制代码
    --1.创建测试表 
    create table #score 
    ( 
    name varchar(20), 
    subject varchar(20), 
    score int 
    ) 
    --2.插入测试数据 
    insert into #score(name,subject,score) values('张三','语文',98) 
    insert into #score(name,subject,score) values('张三','数学',80) 
    insert into #score(name,subject,score) values('张三','英语',90) 
    insert into #score(name,subject,score) values('李四','语文',88) 
    insert into #score(name,subject,score) values('李四','数学',86) 
    insert into #score(name,subject,score) values('李四','英语',88) 
    insert into #score(name,subject,score) values('李明','语文',60) 
    insert into #score(name,subject,score) values('李明','数学',86) 
    insert into #score(name,subject,score) values('李明','英语',88) 
    insert into #score(name,subject,score) values('林风','语文',74) 
    insert into #score(name,subject,score) values('林风','数学',99) 
    insert into #score(name,subject,score) values('林风','英语',59) 
    insert into #score(name,subject,score) values('严明','英语',96) 
    --3.取每个学科的前3名数据 
    select * from 
    ( 
    select subject,name,score,ROW_NUMBER() over(PARTITION by subject order by score desc) as num from #score 
    ) T where T.num <= 3 order by subject 
    --4.删除临时表 
    truncate table #score  
    drop table #score  
    复制代码
     
    语法形式:ROW_NUMBER() OVER(PARTITION BY COL1 ORDER BY COL2) 
    解释:根据COL1分组,在分组内部根据 COL2排序,而此函数计算的值就表示每组内部排序后的顺序编号(组内连续的唯一的)
     
    结果:
  • 相关阅读:
    Macbook键盘的使用基础技巧
    JSTL详解
    为了理想,因为爱情-开课第一天有感(鸡汤向)
    HK游记 Day2迪斯尼(下)
    MP20 MBO issue summary
    音频测量加权
    有没有降噪
    信源编码信源译码和信道编码和译码和加密和解密数字调制和解调和同步
    gcc
    数据挖掘|统计的艺术
  • 原文地址:https://www.cnblogs.com/accumulater/p/6112572.html
Copyright © 2011-2022 走看看