过滤表数据的记录

时间:2014-02-18 15:40:24

标签: tsql

我有一个带tbl_contact_role的表,我所需的输出和表的输入数据如下:

contact_id role_id

1 1

1 2

1 3

2 1

2 2

3 1

4 3

在上面提到的表数据中,我想让contact_id具有角色(1,2)而不是3。

所以上面数据的输出将是contact_id 2,因为它具有我上面提到的两个指定角色,即(1,2)并且没有role_id 3.

期望的输出:

CONTACT_ID

2

提前致谢!

4 个答案:

答案 0 :(得分:1)

select contact_id 
from tbl_contact_role
group by contact_id 
having max(role_id) = 2 
and min(role_id) = 1

答案 1 :(得分:1)

  SELECT ContactID
    FROM ContactRoles 
   WHERE RoleID IN (1,2)
   GROUP BY ContactID
  HAVING COUNT(*) = 2 
EXCEPT 
  SELECT ContactID
    FROM ContactRoles 
   WHERE RoleID IN (3)

SELECT distinct C1.ContactID
  FROM ContactRoles C1 
  JOIN ContactRoles C2
    ON C1.ContactID = C2.ContactID
   AND C1.RoleID = 1
   AND C2.RoleID = 2
  LEFT JOIN ContactRoles C2 
    ON C1.ContactID = C3.ContactID
   AND C3.RoleID = 3
 WHERE C3.ContactID is null

但我怀疑Clalusen的答案将是最好的表现

答案 2 :(得分:0)

如果你的价值很少:

SELECT DISTINCT cr.contact_id
FROM dbo.tbl_contact_role cr
WHERE EXISTS
(
    SELECT 1 FROM dbo.tbl_contact_role cr2
    WHERE cr.contact_id = cr2.contact_id
    AND   cr2.role_id = 1
)
AND EXISTS
(
    SELECT 1 FROM dbo.tbl_contact_role cr2
    WHERE cr.contact_id = cr2.contact_id
    AND   cr2.role_id = 2
)
AND NOT EXISTS
(
    SELECT 1 FROM dbo.tbl_contact_role cr2
    WHERE cr.contact_id = cr2.contact_id
    AND   cr2.role_id = 3
)

contact_idrole_id上的正确索引不是很优雅但效率很高。

Demo

答案 3 :(得分:0)

SELECT ContactID
FROM ContactRoles
GROUP BY ContactID
HAVING SUM(CASE
    WHEN RoleID IN (1,2) THEN 1
    ELSE 99 END) = 2

http://sqlfiddle.com/#!3/3726d/2