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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With