Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get duplicate rows and count based on single column

I need to get the distinct rows based on a single column (code in this case) where there are duplicates of that column value. Along with other information from the row and the number of duplicate rows there are. for example:

ID     code     ownerName
--------------------------
1      001      Mr. Brown
2      001      Mr. Pink
3      002      Mr. White
4      003      Mr. Blonde

I need this query to return

ID     code     ownerName    count
----------------------------------
1      001      Mr. Brown      2

the duplicate row information does not matter which gets returned, but I'm having trouble combining the distinct codes with the count column.

I've tried a query like this:

SELECT DISTINCT A.code, A.ownerName 
FROM Customers A WHERE 
   EXISTS( SELECT * FROM Customers WHERE code = A.code AND id <> A.id) 
order by A.code;

but I'm having trouble getting the count; and with this query

SELECT code, COUNT(*) as numberDuplicates 
FROM Customers GROUP BY code HAVING COUNT(*) > 1

I'm having trouble getting other information I don't want to group by. Can anyone help me figure out how to structure the correct query?

like image 741
user501211 Avatar asked Dec 22 '11 18:12

user501211


1 Answers

If I understand what you are looking for, this should work:

This will select all entries with a non-unique code and return the number of records using that code.

SELECT DISTINCT A.ID, A.Code, A.ownerName, B.Count
FROM Customers A
JOIN (
  SELECT COUNT(*) as Count, B.Code
  FROM Customers B
  GROUP BY B.Code
) AS B ON A.Code = B.Code
WHERE B.Count > 1
ORDER by A.Code;
like image 194
Steven Avatar answered Oct 05 '22 22:10

Steven