Skip to content

Latest commit

 

History

History
68 lines (43 loc) · 3.72 KB

File metadata and controls

68 lines (43 loc) · 3.72 KB
description
This section contains reference documentation for the ROW_NUMBER function.

ROW_NUMBER

Assigns a row number to all the rows in a specified table.

Signature

bigint()

ROW_NUMBER examples

Order transactions by payment date

Order transactions by the payment date and assign them row numbers.

{% code overflow="wrap" %}

select customer_id, payment_date, amount, ROW_NUMBER() OVER(ORDER BY payment_date from payment;

{% endcode %}

customer_idpayment_dateamountrow_number
4162023-02-14 21:21:59.9965772.991
5162023-02-14 21:23:39.9965774.992
2392023-02-14 21:29:00.9965774.993
5922023-02-14 21:41:12.9965776.994
492023-02-14 21:44:52.9965770.995
2642023-02-14 21:44:53.9965773.996
462023-02-14 21:45:29.9965774.997
4812023-02-14 22:03:35.9965772.998
1392023-02-14 22:11:22.9965772.999
5952023-02-14 22:16:01.9965772.9910

Identify the top two transactions by customer, ordered by transaction amount

{% code overflow="wrap" %}

WITH payment_cte as (SELECT ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY amount DESC), customer_id, payment_date, amount from payment) SELECT row_number, customer_id, payment_date, amount from payment_cte WHERE row_number <= 2;

{% endcode %}

row_numbercustomer_idpayment_dateamount
112023-02-15 19:37:12.9965779.99
212023-04-11 08:42:12.9965777.99
122023-04-30 12:16:09.99657710.99
222023-04-30 14:49:39.9965778.99
132023-04-27 18:51:38.9965778.99
232023-03-21 19:19:14.99657710.99
142023-03-18 03:43:10.99657710.99
242023-03-20 11:24:06.99657710.99

Identify customers with the highest number of transactions

Find the number of transactions ranked for each customer. The customer with the highest number of transactions will have a rank of 1, and so on. Order records by the total transactions in descending order. In your rankings, return a unique rank value (to cover multiple customers with the same number of transactions).

{% code overflow="wrap" %}

SELECT customer_id, count(*), ROW_NUMBER() OVER(ORDER BY count(*) DESC, customer_id ASC) from payment GROUP BY customer_id;

{% endcode %}

customer_id count row_number
148 45 1
245 42 2
144 39 3
253 39 4
410 36 5
368 34 6


\