根据SQL中相同ID的其他记录筛选出记录

时间:2016-01-27 23:29:02

标签: sql sql-server select where

我的表架构如下:

Table Name: Quality

ID     Name      Type
--     ----      ----
1      XYZ       S1
1      XYZ       B1
1      XYZ       S2
1      XYZ       R1
2      ABC       B1
2      ABC       B2
2      ABC       R1 
2      ABC       U1
3      PQR       B1
3      PQR       B2
3      PQR       R2
3      PQR       R1
4      AAA       B1
4      AAA       S1
5      BBB       B1
5      BBB       B2
5      BBB       U2

我想过滤掉那些Type为B1但不应该是(其他行中的R1和U1)的ID。还有那些类型为B2但它不是(其他行中的R2和S2)

的ID

这里输出应该是

ID     Name      Type
--     ----      ----
2      ABC       B2
4      AAA       B1
5      BBB       B1

我的查询是关于nto给出正确的结果:

SELECT 
      ID , NAME , TYPE      

FROM
       QUALITY Q

WHERE
       (Q.TYPE IN ('B1') AND (Q.TYPE Not IN ('R1', 'U1'))
       OR
       (Q.TYPE IN ('B2') AND (Q.TYPE Not IN ('R2', 'U2'))

我的查询一次运行一条记录,所以我没有得到正确的结果。如何使此查询检查该特定ID的每条记录以查找TYPE?

任何帮助都非常有用。

2 个答案:

答案 0 :(得分:1)

select * from 
quality q 
where 
(q.type = 'b1' and q.id not in (select q2.id from quality q2 where q2.type in ('r1','u1'))
or
(q.type = 'b2' and q.id not in (select q3.id from quality q3 where q3.type in ('r2','u2'))

答案 1 :(得分:1)

您可以使用NOT EXISTS

SELECT *
FROM Quality q
WHERE
    (Type = 'B1' AND NOT EXISTS(SELECT 1 FROM Quality WHERE ID = q.ID AND Type IN ('R1', 'U1')))
    OR (Type = 'B2' AND NOT EXISTS(SELECT 1 FROM Quality WHERE ID = q.ID AND Type IN ('R2', 'U2')))