Skip to content
Advertisement

SQL: Running Total of Occurrences

I am using Metabase with a PostgreSQL implementation.

Running Count of Occurrences

I’d like to achieve the outcome in the photo. I wish to include a column that counts how many times a field has occurred above. It should include the current instance as well.

Other examples I’ve seen have simply counted total occurrences. As I am ordering by date, I do not wish to count occurrences that happen after the date.

Advertisement

Answer

You can use window functions in Postgres:

select name, date, row_number() over (partition by name order by date) as seqnum
from t;

You probably also want order by date at the end of the query to guarantee that the results are in date order.

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