需要您的SQL帮助。我跟着表:
USERID RuleID
1 101
1 102
1 103
2 101
2 103
3 101
3 102
我想获得存在RuleID 102的所有用户ID,但是没有规则101和103.例如在上面的示例中,它应该返回UserID 3 ..
任何帮助将不胜感激
答案 0 :(得分:3)
此查询将返回仅具有102而不包含其他内容的用户ID
select userid
from mytable
group by userid
having count(case when ruleid <> 102 then 1 end) = 0
如果您只想要包含102但不包含101和103
的行SELECT USERID
FROM yourTable
GROUP BY USERID
HAVING
(
COUNT(CASE WHEN RuleID = 101 THEN 1 END) = 0 OR
COUNT(CASE WHEN RuleID = 103 THEN 1 END) = 0
)
AND COUNT(CASE WHEN RuleID = 102 THEN 1 END) > 0
以下是第二个查询的运行演示的链接:
答案 1 :(得分:0)
SELECT userid
FROM sometable
WHERE RuleID = 101
AND userid NOT IN (SELECT userid FROM sometable WHERE RuleID IN (102, 103))