Yes, you can reset row_number() to 1 once it reaches a distinct value by using the PARTITION BY clause.
For example, consider the following table named "sales":
| Sale_id | Date | Product | Revenue | |--------|------------|---------|---------| | 1 | 2022-01-01 | A | 100 | | 2 | 2022-01-02 | B | 150 | | 3 | 2022-01-02 | A | 200 | | 4 | 2022-01-03 | A | 300 | | 5 | 2022-01-03 | B | 250 |
To reset row_number() to 1 once it reaches a distinct value of "Date", you can use the following SQL query:
SELECT
ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Sale_id) AS row_number,
Sale_id,
Date,
Product,
Revenue
FROM sales;
The result would be:
| rownumber | Saleid | Date | Product | Revenue | |------------|--------|------------|---------|---------| | 1 | 1 | 2022-01-01 | A | 100 | | 1 | 2 | 2022-01-02 | B | 150 | | 2 | 3 | 2022-01-02 | A | 200 | | 1 | 4 | 2022-01-03 | A | 300 | | 2 | 5 | 2022-01-03 | B | 250 |
As you can see, the row_number() resets to 1 whenever the value of "Date" changes.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-06-09 11:00:00 +0000
Seen: 13 times
Last updated: May 08 '22
How do you log Python data into a database?
How can the SQL debug mode be activated in PostgreSQL version 15.2?
How to deal with an operational error when connecting Django to MySQL?
What is the method for choosing data FROM a stored procedure?
How can SQL/PLSQL blocks be stripped of their comments?
What is the process for initializing Java UDFs in Spark?
How to set up Database First configuration in Entity Framework 7 for MVC 6?