Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Another SQL Show all records in a Group By, with a HAVING

We accidentally let in some duplicate clients

id Lookup
1 abc
2 abc
3 def
4 def
5 ghi
6 ghi
7 j
8 k
9 l

I have a query that shows the duplicate Lookup values

SELECT Lookup, COUNT (Lookup)
  FROM Clients
  GROUP BY Lookup
  HAVING COUNT(*) > 1

That produces

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Lookup (No name)
abc 2
def 2
ghi 2

I’d like to see the id numbers next to those.

id Lookup
1 abc
2 abc
3 def
4 def
5 ghi
6 ghi

I found MySQL – Group and total, but return all rows in each group which looks very close to what I’m doing. But:

  SELECT a.id, a.Lookup
  FROM Clients as a
  JOIN (SELECT id, Lookup
  FROM Clients
  GROUP BY Lookup, id
  HAVING COUNT(*) > 1) as b
  ON a.id = b.id

Produces an empty result set. (I tried with and without the Lookup in "JOIN (SELECT id, Lookup").

That looks to me like it should work. What am I overlooking?

>Solution :

You must join it on the Lookup instead of id

SELECT c.*
FROM Clients c
JOIN (
    SELECT Lookup, COUNT (Lookup)
    FROM Clients
    GROUP BY Lookup
    HAVING COUNT(*) > 1
) cnt ON cnt.Lookup = c.Lookup
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading