SQL进阶——GROUP BY 和 PARTITION BY

运行环境 win10 / oracle(DB11g)

一、rank()dense_rank()row_number()

-- 创表
create table teams_5
(
    member varchar(6),
    team   varchar(4),
    age   SMALLINT
)
;

insert into teams_5 values ('大木', 'A', 28);
insert into teams_5 values ('一件', 'A', 19);
insert into teams_5 values ('新特', 'A', 23);
insert into teams_5 values ('山田', 'B', 40);
insert into teams_5 values ('九本', 'C', 30);
insert into teams_5 values ('乔天', 'D', 28);
insert into teams_5 values ('野野宫', 'D', 28);
insert into teams_5 values ('加藤', 'D', 24);
insert into teams_5 values ('新城', 'D', 22);

-- 排序
select member, team, age,
       rank() over(partition by team order by age desc) rn,
       dense_rank() over(partition by team order by age desc) dense_rn,
       row_number() over(partition by team order by age desc) row_num 
  from teams_5
 order by team, rn
;

结果:

MEMBER TEAM        AGE         RN   DENSE_RN    ROW_NUM
------ ---- ---------- ---------- ---------- ----------
大木   A            28          1          1          1
新特   A            23          2          2          2
一件   A            19          3          3          3
山田   B            40          1          1          1
九本   C            30          1          1          1
乔天   D            28          1          1          1
野野宫 D            28          1          1          2
加藤   D            24          3          2          3
新城   D            22          4          3          4

rn 位次有跳动,row_num连续

二、用求余数分组 (抽样)

-- 从原来的表中抽出(大约)五分之一的数据
select *
  from sometbl
 where mod(seq, 5) = 0
;

--如果没有连续编号,用row_number()函数生成
select * 
  fromselect col,
                row_number() over(order by col) as seq
          from somtbl)
 where mod(seq, 5) = 0
 ;

内容多来自 《SQL进阶教材》,仅做笔记。

你可能感兴趣的:(sql)