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

Select distinct rows with same value in another column

I have a table like this:

+--------+----------+
|PersonID|IsDomestic|
+--------+----------+
|1       |1         |
+--------+----------+
|1       |0         |
+--------+----------+
|2       |1         |
+--------+----------+
|2       |1         |
+--------+----------+
|2       |1         |
+--------+----------+
|1       |1         |
+--------+----------+
|3       |0         |
+--------+----------+
|4       |1         |
+--------+----------+

If the same PersonId have at least one 0 value in IsDomestic column then shouldn’t return this PersonId but if PersonId have only 1 values then should return this PersonId but only once. This is result from the table:

+--------+
|PersonID|
+--------+
|2       |
+--------+
|4       |
+--------+

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

>Solution :

What you need is a HAVING with a conditional aggregate:

SELECT PersonID
FROM dbo.YourTable
GROUP BY PersonID
HAVING COUNT(CASE IsDomestic WHEN 0 THEN 1 END) = 0;
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