Skip to content
Advertisement

How to order occurrences counting from 1 to n occurrences

I have a table that contains several columns, but for the task, the important ones are id end created_date, where id can repeat.

Sample data:

+--------+--------------+
|  id    | created_date |
+--------+--------------+
| 12345  | 2020-05-01   |
| 12345  | 2020-04-23   |
| 54321  | 2020-05-12   |
| 12345  | 2020-06-13   |
| 54321  | 2020-01-03   |
+--------+--------------+

I need to write a query that creates a new column that enumerate the occurrences of each id, ordered by the ascending created_date. The output must be something like the following:

+--------+--------------+------------------+
|  id    | created_date | occurrence_count |
+--------+--------------+------------------+
| 12345  | 2020-04-23   |                1 |
| 12345  | 2020-05-01   |                2 |
| 12345  | 2020-06-13   |                3 |
| 54321  | 2020-01-03   |                1 |
| 54321  | 2020-05-12   |                2 |
+--------+--------------+------------------+

What query would output this result table?

Advertisement

Answer

you can use window function

select t.*,
   row_number() over (partition by id order by created_date asc) as occurrence_count
 from t
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement