选择行而不使用'不在'条款

时间:2015-07-07 04:40:53

标签: sql sql-server tsql subquery case

我有一张这样的表:

+----+----------+
| ID |    WA    |
+----+----------+
|124 | benefit  |
|124 | ordane   |
|124 | military |
|124 | para     |
|125 | benefit  |
|126 | benefit  |
|126 | ordane   |
|127 | benefit  |
|127 | ordane   |
|127 | military |
|128 | benefit  |
+----+----------+

我希望这些ID与WA ='有益的'并使用WA =' ordane'排除这些ID。我想避免not innot existsexcept。我尝试了CASE声明,但没有得到它。还有其他方法吗?谢谢!

1 个答案:

答案 0 :(得分:3)

只需使用HAVING

进行后期聚合过滤
SELECT id FROM t GROUP BY id 
HAVING SUM(CASE WHEN WA='benefit' THEN 1 ELSE 0 END)>0
AND SUM(CASE WHEN WA='ordane' THEN 1 ELSE 0 END)=0