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

To check if group of records contain a boolean in SQL

So I have this table and in SQL as below

Table : Fruits

Id = int,
Name = varchar,
Type = varchar,
isPrimary = bit

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

Id Name Type isPrimary
1 Apple Type A 1
2 Apple Type B 0
3 Mango Type A 0
4 Mango Type B 0
5 Mango Type C 1
6 Mango Type D 0
7 Orange Type A 0
8 Orange Type B 0
9 Orange Type C 0
10 Orange Type D 0

I need to get records where a group does not contain isPrimary =1. So in the above case, Orange is the record that I will get.

This is my query, but this is not working as expected.

Select Name from fruits
Group by Name
having isPrimary != 1

How do I go about fixing it?

>Solution :

You can use a subquery. First, we get the name where isprimary=1 in the "inner query," then we excise the name from the outer query. or you can use the left join with the same table to get the same result.

-- using left join
select distinct a.name from #u a
left join
(
select * from #u where Isprimary=1
)b on a.name=b.name 
where b.name is null

-- using subquery
 select distinct name from #u  where name not in (select name from #u where Isprimary=1)
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