Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select non-distinct rows with a distinct on multiple columns

Tags:

sql

sql-server

I have found many answers on selecting non-distinct rows where they group by a singular column, for example, e-mail. However, there seems to have been issue in our system where we are getting some duplicate data whereby everything is the same except the identity column.

SELECT DISTINCT 
      COLUMN1,
      COLUMN2,
      COLUMN3,
      ...
      COLUMN14
  FROM TABLE1

How can I get the non-distinct rows from the query above? Ideally it would include the identity column as currently that is obviously missing from the distinct query.

like image 866
ediblecode Avatar asked Dec 25 '22 14:12

ediblecode


2 Answers

select COLUMN1,COLUMN2,COLUMN3 
from TABLE_NAME 
group by COLUMN1,COLUMN2,COLUMN3 
having COUNT(*) > 1
like image 185
kanishka Avatar answered Dec 27 '22 03:12

kanishka


With _cte (col1, col2, col3, id) As
    (
        Select cOl1, col2, col3, Count(*)
          From mySchema.myTable
          Group By Col1, Col2, Col3
          Having Count(*) > 1
    )
Select t.*
From _Cte As c
Join mySchema.myTable As t
On c.col1 = t.col1
And c.col2 = t.col2
And c.col3 = t.col3
like image 38
Rachel Ambler Avatar answered Dec 27 '22 03:12

Rachel Ambler