Skip to content
Advertisement

Incrementing count ONLY for duplicates in MySQL

Here is my MySQL table. I updated the question by adding an ‘id’ column to it (as instructed in the comments by others).

I want to add a new column called row_num to assign an incrementing number ONLY for duplicates, as shown below. Order of the results does not matter.

I followed this answer and came up with the code below. But following code adds a count of ‘1’ to non-duplicate values too, how can I modify below code to add a count only for duplicates?

Advertisement

Answer

I am assuming that id is the column that defines the order on the rows.

In MySQL 8 you can use row_number() to get the number of each data_id and a CASE with EXISTS to exclude the rows which have no duplicate.

In older versions you can use a subquery counting the rows with the same data_id but smaller id. With an EXISTS in a HAVING clause you can exclude the rows that have no duplicate.

db<>fiddle

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