row_number
Function
The row_number function is used to calculate the row number. It increments starting from 1.
Usage Restrictions
The usage restrictions for window functions are as follows:
- Window functions can only appear in SELECT statements.
- Window functions cannot be nested with other window functions or aggregate functions.
- Window functions cannot be used together with aggregate functions at the same level.
Syntax
row_number() over([partition_clause] [orderby_clause])
Parameters
| Parameter | Mandatory | Description |
|---|---|---|
| partition_clause | No | Specifies the partition. Rows with the same value in the partition column are considered to be within the same window. |
| orderby_clause | No | Specifies how data is sorted within a window. |
Return Values
Returns a value of type INT.
Examples
To facilitate understanding of the function's usage, source data is provided along with function-related examples. Create the logs table and add data with the following example command:
CREATE TABLE logs ( cookieid string, createtime string, pv INT ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' stored as textfile;
Add data as follows:
cookie1 2015-04-10 1 cookie1 2015-04-11 5 cookie1 2015-04-12 7 cookie1 2015-04-13 3 cookie1 2015-04-14 2 cookie1 2015-04-15 4 cookie1 2015-04-16 4 cookie2 2015-04-10 2 cookie2 2015-04-11 3 cookie2 2015-04-12 5 cookie2 2015-04-13 6 cookie2 2015-04-14 3 cookie2 2015-04-15 9 cookie2 2015-04-16 7
Example: Group all records by cookieid, sort by pv in descending order, and return the sequence number for each row within the group. Example command:
select cookieid, createtime, pv,
row_number() over (partition by cookieid order by pv desc) as index
from logs;
-- Result:
cookie1 2015-04-12 7 1
cookie1 2015-04-11 5 2
cookie1 2015-04-16 4 3
cookie1 2015-04-15 4 4
cookie1 2015-04-13 3 5
cookie1 2015-04-14 2 6
cookie1 2015-04-10 1 7
cookie2 2015-04-15 9 1
cookie2 2015-04-16 7 2
cookie2 2015-04-13 6 3
cookie2 2015-04-12 5 4
cookie2 2015-04-11 3 5
cookie2 2015-04-14 3 6
cookie2 2015-04-10 2 7 What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot