文章目录
自增行号函数
- 按照值排序时产生一个自增行号,不会重复。针对相同数据,先查出的排名在前,没有重复值
sql
复制代码
SELECT
row_number() OVER (PARTITION BY EventDate ORDER BY cnt ASC) AS rno,
OS,
EventDate,
cnt
FROM
(
SELECT
OS,
cnt,
EventDate
FROM
(
SELECT
EventDate,
OS,
uniqExact(UserID) AS cnt
FROM tutorial.hits_v1
GROUP BY
EventDate, OS
) AS t
) AS T
limit 20
跳跃排名函数
- 跳跃排名,值相等时会重复,会产生空位。相同数据排名相同,比如并列第1,则两行数据(这里为rank列)都标为1,下一位将是第3名,中间的2被直接跳过了。排名存在重复值。
sql
复制代码
SELECT
rank() OVER (PARTITION BY EventDate ORDER BY cnt ASC) AS rno,
OS,
EventDate,
cnt
FROM
(
SELECT
OS,
cnt,
EventDate
FROM
(
SELECT
EventDate,
OS,
uniqExact(UserID) AS cnt
FROM tutorial.hits_v1
GROUP BY
EventDate, OS
) AS t
) AS T
limit 20
连续排名函数
- 连续排名,值相等时会重复,不会产生空位。比如两条并列第1,则两行数据(这里为rank列)都标为1,下一个排名将是第2名。
sql
复制代码
SELECT
dense_rank() OVER (PARTITION BY EventDate ORDER BY cnt ASC) AS rno,
OS,
EventDate,
cnt
FROM
(
SELECT
OS,
cnt,
EventDate
FROM
(
SELECT
EventDate,
OS,
uniqExact(UserID) AS cnt
FROM tutorial.hits_v1
GROUP BY
EventDate, OS
) AS t
) AS T
limit 20
窗口计数函数
sql
复制代码
SELECT
number AS x,
count() OVER (PARTITION BY intDiv(x, 3) ORDER BY x ASC) AS cnt
FROM numbers(10)
SETTINGS max_block_size = 3
Query id: dfeb20ae-1745-4496-877d-74d8aea95414
┌─x─┬─cnt─┐
│ 0 │ 1 │
│ 1 │ 2 │
│ 2 │ 3 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 3 │ 1 │
│ 4 │ 2 │
│ 5 │ 3 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 6 │ 1 │
│ 7 │ 2 │
│ 8 │ 3 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 9 │ 1 │
└───┴─────┘
窗口最大值函数
sql
复制代码
SELECT
number AS x,
max(x) OVER (PARTITION BY intDiv(x, 3) ORDER BY x DESC) AS cnt
FROM numbers(10)
SETTINGS max_block_size = 3
Query id: bdb8038f-0d2e-442b-a4fd-258787f5738f
┌─x─┬─cnt─┐
│ 2 │ 2 │
│ 1 │ 2 │
│ 0 │ 2 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 5 │ 5 │
│ 4 │ 5 │
│ 3 │ 5 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 8 │ 8 │
│ 7 │ 8 │
│ 6 │ 8 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 9 │ 9 │
└───┴─────┘
窗口最小值函数
sql
复制代码
SELECT
number AS x,
MIN(x) OVER (PARTITION BY intDiv(x, 3) ORDER BY x ASC) AS cnt
FROM numbers(10)
SETTINGS max_block_size = 3
Query id: e763ce9f-3eba-40a6-ad78-b0ae20dcfdda
┌─x─┬─cnt─┐
│ 0 │ 0 │
│ 1 │ 0 │
│ 2 │ 0 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 3 │ 3 │
│ 4 │ 3 │
│ 5 │ 3 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 6 │ 6 │
│ 7 │ 6 │
│ 8 │ 6 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 9 │ 9 │
└───┴─────┘
窗口平均值函数
sql
复制代码
SELECT
number AS x,
avg(x) OVER (PARTITION BY intDiv(x, 3) ORDER BY x ASC) AS cnt
FROM numbers(10)
SETTINGS max_block_size = 3
Query id: c9b8ab1b-8a6f-4191-a248-f8a589becb5a
┌─x─┬─cnt─┐
│ 0 │ 0 │
│ 1 │ 0.5 │
│ 2 │ 1 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 3 │ 3 │
│ 4 │ 3.5 │
│ 5 │ 4 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 6 │ 6 │
│ 7 │ 6.5 │
│ 8 │ 7 │
└───┴─────┘
┌─x─┬─cnt─┐
│ 9 │ 9 │
└───┴─────┘