zoukankan      html  css  js  c++  java
  • row_number() over(partition by... order by...)分组聚合排序

    row_number() over(partition by... order by...)分组聚合排序

    ROW_NUMBER() OVER(
        [PARTITION BY column_1, column_2,…]
        [ORDER BY column_3,column_4,…] [desc/asc]
    )
    
    PARTITION BY 分组通过
    ORDER BY 排序通过
    

    sqlserver用法示例

    创建表

    use dbo;
    IF object_id('employee') is not null drop table employee;
    
    create table employee(employee int, departid int,salary decimal(18,2));
    
    insert into employee values(1,10,5500.00);
    insert into employee values(2,10,4500.00);
    insert into employee values(3,20,1900.00);
    insert into employee values(4,20,4800.00);
    insert into employee values(5,40,6500.00);
    insert into employee values(6,40,14500.00);
    insert into employee values(7,40,44500.00);
    insert into employee values(8,50,6500.00);
    insert into employee values(9,50,7500.00);
    
    select * from employee;
    
    employee departid salary
    1 10 5500.00
    2 10 4500.00
    3 20 1900.00
    4 20 4800.00
    5 40 6500.00
    6 40 14500.00
    7 40 44500.00
    8 50 6500.00
    9 50 7500.00

    先分组再排序(先排序partition by后面的,再排序order by后面的)

    select
      employee
      ,departid
      ,salary
      ,row_number() over(partition by departid order by salary) sno
    from employee
    

    结果

    employee departid salary
    2 10 4500.00
    1 10 5500.00
    3 20 1900.00
    4 20 4800.00
    5 40 6500.00
    6 40 14500.00
    7 40 44500.00
    8 50 6500.00
    9 50 7500.00
  • 相关阅读:
    SQL生成上百万条数据 及分页 长沙
    aspx或ashx里面多个方法 进行ajax调用 长沙
    C# IO操作,文件 文件夹 长沙
    Reperter多层嵌套 长沙
    解读WPF中事件
    WPF 神话之Binding对象二
    WPF 神话之Binding对象一
    明白就好
    导出Execl和读取Execl文件
    新加入博客园,嘿嘿
  • 原文地址:https://www.cnblogs.com/Neroi/p/15617275.html
Copyright © 2011-2022 走看看