简体   繁体   中英

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       |
+--------+

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM