Skip to content
Advertisement

SQL Sorted Count

I have the following table sorted by date:

date id
9/1/20 1
9/1/20 2
9/3/20 1
9/4/20 3
9/4/20 2
9/6/20 1

I’d like to add a count column for each id so that the first count for each id is the earliest date and latest date would receive the highest count for each id:

date id count
9/1/20 1 1
9/1/20 2 1
9/3/20 1 2
9/4/20 3 1
9/4/20 2 2
9/6/20 1 3

How can I structure my Postgresql query to assemble this count column?

Advertisement

Answer

This looks like row_number():

select t.*,
       row_number() over (partition by id order by date) as seqnum
from t
order by date, id;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement