mirror of
https://github.com/ClickHouse/ClickHouse.git
synced 2024-11-25 09:02:00 +00:00
74 lines
2.5 KiB
Markdown
74 lines
2.5 KiB
Markdown
---
|
|
slug: /en/sql-reference/window-functions/rank
|
|
sidebar_label: rank
|
|
sidebar_position: 6
|
|
---
|
|
|
|
# rank
|
|
|
|
Ranks the current row within its partition with gaps. In other words, if the value of any row it encounters is equal to the value of a previous row then it will receive the same rank as that previous row.
|
|
The rank of the next row is then equal to the rank of the previous row plus a gap equal to the number of times the previous rank was given.
|
|
|
|
The [dense_rank](./dense_rank.md) function provides the same behaviour but without gaps in ranking.
|
|
|
|
**Syntax**
|
|
|
|
```sql
|
|
rank (column_name)
|
|
OVER ([[PARTITION BY grouping_column] [ORDER BY sorting_column]
|
|
[ROWS or RANGE expression_to_bound_rows_withing_the_group]] | [window_name])
|
|
FROM table_name
|
|
WINDOW window_name as ([[PARTITION BY grouping_column] [ORDER BY sorting_column])
|
|
```
|
|
|
|
For more detail on window function syntax see: [Window Functions - Syntax](./index.md/#syntax).
|
|
|
|
**Returned value**
|
|
|
|
- A number for the current row within its partition, including gaps. [UInt64](../data-types/int-uint.md).
|
|
|
|
**Example**
|
|
|
|
The following example is based on the example provided in the video instructional [Ranking window functions in ClickHouse](https://youtu.be/Yku9mmBYm_4?si=XIMu1jpYucCQEoXA).
|
|
|
|
Query:
|
|
|
|
```sql
|
|
CREATE TABLE salaries
|
|
(
|
|
`team` String,
|
|
`player` String,
|
|
`salary` UInt32,
|
|
`position` String
|
|
)
|
|
Engine = Memory;
|
|
|
|
INSERT INTO salaries FORMAT Values
|
|
('Port Elizabeth Barbarians', 'Gary Chen', 195000, 'F'),
|
|
('New Coreystad Archdukes', 'Charles Juarez', 190000, 'F'),
|
|
('Port Elizabeth Barbarians', 'Michael Stanley', 150000, 'D'),
|
|
('New Coreystad Archdukes', 'Scott Harrison', 150000, 'D'),
|
|
('Port Elizabeth Barbarians', 'Robert George', 195000, 'M'),
|
|
('South Hampton Seagulls', 'Douglas Benson', 150000, 'M'),
|
|
('South Hampton Seagulls', 'James Henderson', 140000, 'M');
|
|
```
|
|
|
|
```sql
|
|
SELECT player, salary,
|
|
rank() OVER (ORDER BY salary DESC) AS rank
|
|
FROM salaries;
|
|
```
|
|
|
|
Result:
|
|
|
|
```response
|
|
┌─player──────────┬─salary─┬─rank─┐
|
|
1. │ Gary Chen │ 195000 │ 1 │
|
|
2. │ Robert George │ 195000 │ 1 │
|
|
3. │ Charles Juarez │ 190000 │ 3 │
|
|
4. │ Douglas Benson │ 150000 │ 4 │
|
|
5. │ Michael Stanley │ 150000 │ 4 │
|
|
6. │ Scott Harrison │ 150000 │ 4 │
|
|
7. │ James Henderson │ 140000 │ 7 │
|
|
└─────────────────┴────────┴──────┘
|
|
``` |