查询以过滤掉否定的行

时间:2016-12-13 11:12:11

标签: sql sql-server

我需要使用否定值过滤掉行。即我想删除一列匹配的所有行,并且有两行具有否定值。即来自

ID, Val, Details
0,   4,  "Details 0 1..."
1,   5,  "Details 1 1..."
1,   7,  "Details 1 2..."
1,  -5,  "Details 1 3..."
2,   9,  "Details 2 1..."

我想要

ID, Val, Details
0,   4,  "Details 0 1..."
2,   9,  "Details 2 1..."

因为行1,5 ...和1,-5,...否定将ID标记为无效。我很难找到一个干净的方法来做到这一点。

1 个答案:

答案 0 :(得分:5)

使用NOT EXISTS验证ID没有“否定值”:

select *
from tablename t
where not exists (select 1 from tablename t1
                  join tablename t2
                      on t1.ID = t2.ID and t1.Val = -t2.Val
                  where t1.ID = t.ID)