sql select语句排除具有不同值的相同行

时间:2014-03-25 11:10:20

标签: sql

我正在使用Sql Server 2008并尝试实现如下:

现有表格:

+--------+-------------+--------+
| ID     | COUNTRY     | STATUS |
+--------+-------------+--------+
| 1      | UK          |   0    |
| 2      | UK          |   1    |
| 3      | USA         |   0    |
| 4      | Greece      |   0    |
| 5      | Italy       |   1    |
+-------------------------------+

我尝试查询Where STATUS = 0并同时排除所有这些行,如果相同的国家/地区有两个不同的状态(在我的情况下在上表中排除英国)

预期结果:

+--------+-------------+--------+
| ID     | COUNTRY     | STATUS |
+--------+-------------+--------+
| 3      | USA         |   0    |
| 4      | Greece      |   0    |
+-------------------------------+

提前致谢!

2 个答案:

答案 0 :(得分:1)

请尝试:

select * From tbl x 
where STATUS=0 and
    (select COUNT(*) from tbl y 
    where y.COUNTRY=x.COUNTRY and y.STATUS=1)=0

答案 1 :(得分:0)

试试这个

SELECT * 
FROM  Table1
WHERE STATUS = 0 AND
Country NOT IN (SELECT Country FROM Table1 WHERE Status = 1)

<强> Fiddle Demo

<强> Outpit:

+--------+-------------+--------+
| ID     | COUNTRY     | STATUS |
+--------+-------------+--------+
| 3      | USA         |   0    |
| 4      | Greece      |   0    |
+-------------------------------+