I want to incrementally count the number of repeated instances in a table, so if I have a table like this:
id | name | status |
-----------------------
1 | John | 1 |
2 | Jane | 1 |
4 | John | 1 |
5 | John | 1 |
6 | Jane | 1 |
7 | John | 1 |
Using the column "name" as reference, the output would be
id | name | status | count |
------------------------------
1 | John | 1 | 1 |
2 | Jane | 1 | 1 |
4 | John | 1 | 2 |
5 | John | 1 | 3 |
6 | Jane | 1 | 2 |
7 | John | 1 | 4 |
The DBMS implementation is MySQL, version 5.6
In MySQL 5.x, where window functions are not available, one option uses a correlated subquery:
You could also do this with user variables:
There are pros and cons to both approaches. The second solution scales better than the first against a large dataset, however user variables are tricky in MySQL, and are now officially planned for deprecation in a future version.