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

SQL finding mismatches within the same column

SQL Noob here.
I’m struggling with a (hopefully) simple SQL query and would appreciate if someone could help me understand if what I’m trying to do is even possible. I already completed the task outside SQL so this is just my curiosity.

Task is simple.
I have a Table with millions of Codes. There are 12 digit codes always starting with ‘00000’ and their 7 digit equivalents. (like 000001234567 and 1234567)
I’d need to identify all 12 digit codes that DO NOT have equivalent 7 digit code within the same column.

Any help appreciated.

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

This is the data of the table :

Code
000001234567
1234567
000002345678
2345678
000003456789
000004567891
000005678912

and the expected output is :

Code
000003456789
000004567891
000005678912

>Solution :

You can use TRIM() function and HAVING clause along with GROUP BY such as

 SELECT CONCAT('00000',TRIM(LEADING '0' FROM code))
   FROM t
  GROUP BY CONCAT('00000',TRIM(LEADING '0' FROM code)) 
  HAVING COUNT(TRIM(LEADING '0' FROM code))=1 

Demo

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