Skip to content
Advertisement

How can I get a count for duplicates in SQL Server and write the result for each row to a column (without excluding rows)?

Suppose I have a table, like this:

MyTable

How can I get the number of occurrences a name appears in a given column, and then display that number to new column?

For example, this would be my desired output:

Instinctively, I want to use something like

However, this not only omits the Number column, but it also doesn’t return ALL the results. I want to list all the results back, without excluding any rows, and then simply put a column with the number of times Name appears in the table.

Searching stackoverflow (and google), I found some of these results:

Count duplicate values in SQL Server and display as another column

Count Duplicate Data in Column and Display Once Per Row – SQL

Finding duplicate values in a SQL table

The problem with these links and everything I am finding online is that they are all using GROUP BY. Is there a simple, clean way to get the count of each name in the table, and then write the number to a column for each row?

Advertisement

Answer

Maybe you simply need a windowed COUNT():

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