N3xtchen 的数字花园

Search

Search IconIcon to open search

SQL 窗口函数

上次更新于 Feb 17, 2023 编辑源文件

1
2
3
4
5
<窗口函数>([col2]) OVER (
  [PARITION BY col1]
  [ORDER BY col2]
  [RANGE BETWEEN [START] AND [END]] -- 划窗
)

# 排名函数

# 全局排序

<排序函数>() OVER (ORDER BY col)

排序函数:

1
2
3
4
5
6
7
8
9
CREATE TABLE order_list (val int);
INSERT INTO order_list VALUES (1),(2),(2),(3),(4),(6),(7);
SELECT
  val,
  ROW_NUMBER() OVER (ORDER BY val),
  RANK() OVER (ORDER BY val),
  DENSE_RANK() OVER (ORDER BY val),
  ROUND(PERCENT_RANK()  OVER (ORDER BY val), 2)
FROM order_list

# 分组排序

这个是个很常见的场景,比如:

1
2
3
4
5
6
7
8
9
CREATE TABLE group_list (grp varchar(2), val int);
INSERT INTO group_list VALUES ('a', 1),('a',2),('a',3),('b',1),('b',2),('b',3),('b',4);
SELECT
  grp, val,
  ROW_NUMBER() OVER (PARTITION BY grp ORDER BY val),
  RANK() OVER (PARTITION BY grp ORDER BY val),
  DENSE_RANK() OVER (PARTITION BY grp ORDER BY val),
  ROUND(PERCENT_RANK() OVER (PARTITION BY grp ORDER BY val),2)
FROM group_list;