Skip to content
Advertisement

How to use `ROW_NUMBER` but grouping by days in PostgreSQL?

I have a table (t1) like this:

(and so on)

What I want to do is to get a new autoincrement column based on day index, starting by 1.

I guess I could achieve that by using something like ROW_NUMBER:

But with this query I get the following:

Which is in a sense something similar to what I’m looking for, but just in the opposite direction. That is, instead of increasing the index in each partition (for each day), what I want is that it remains constant, and increases only as the day increases. What I would like to obtain as a result would be the following.

Advertisement

Answer

You can do it by using CTE. You set the row number by date then join to t1 table.

Result here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement