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 group but return wrong result

I have a table:

name code
a 1
a 2
b 1
b 2
c 2
c 3

want to get this result where code =1 and group by name

name code
a 1
a 2
b 1
b 2

I tried this query:

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

select name, code where code=1 and group by name , code

but I just get this:

name code
a 1
b 1

How can I fix it to get the correct results?

>Solution :

You appear to want all of the records for names that contain a code = 1

SELECT *
FROM Example 
WHERE name in
(SELECT name from Example WHERE Code='1')

fiddle

CTE version as suggested by Isolated

WITH CTE as
(
  SELECT * FROM EXAMPLE WHERE Code='1'
)
SELECT E.*
FROM CTE C
INNER JOIN Example E ON C.name=E.name 
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