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

Return distinct results that appear more than once

I have the following data:

    ID  Site
    2   NULL
    2   32
    3   6
    4   7
    8   12
    8   13
    9   14
    9   14

Result should be:

    ID  Site
    2   NULL
    2   32
    8   12
    8   13

Note that the result find unique combinations of ID and Site that repeat more than once for a given ID.

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

I did the following query but does not return the result:

 select  distinct id, site
 from Table1  
 group by id, site
 having count(*) > 1
 order by id

>Solution :

SELECT
   ID,
   site
FROM table1
WHERE ID IN (
   SELECT ID
   FROM (
      SELECT ID ,site
      FROM table1 
      GROUP BY ID ,site
   ) x
   GROUP BY ID
   HAVING count(*)>1
)

See: DBFIDDLE

  • The SELECT ID, site FROM table1 GROUP BY ID, site will select the distinct values.
  • Then, using HAVING count(*) > 1, only the IDs that appear more than once are filtered.

P.S. You should try to avoid using DISTINCT and GROUP BY in one query. It makes life so much more complicated when you do that … 😉

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