如果我想找到只有单个ruleid为2的联系人,需要有关sql的帮助。因此输出应该是联系人ID 1和7。 我不是在寻找联系人ID 5& 6在输出中,因为它们有多个规则,即使它们有规则2
Contactid ruleid
1 2
5 3
5 2
6 4
6 2
7 2
有人可以帮忙解决这个问题。
答案 0 :(得分:2)
您可以尝试这样的事情:
SELECT Contactid FROM <YOURTABLE>
WHERE ruleid = 2
AND Contactid NOT IN
(SELECT Contactid FROM <YOURTABLE>
WHERE ruleid <> 2)
答案 1 :(得分:1)
WITH your_table_name as(
SELECT 1 AS Contactid , 2 AS ruleid FROM DUAL
UNION ALL
SELECT 5 AS Contactid , 3 AS ruleid FROM DUAL
UNION ALL
SELECT 5 AS Contactid , 2 AS ruleid FROM DUAL
UNION ALL
SELECT 6 AS Contactid , 4 AS ruleid FROM DUAL
UNION ALL
SELECT 6 AS Contactid , 2 AS ruleid FROM DUAL
UNION ALL
SELECT 7 AS Contactid , 2 AS ruleid FROM DUAL
)
SELECT t.* FROM (
SELECT Contactid FROM your_table_name
WHERE ruleid = 2
GROUP BY Contactid
HAVING COUNT(*) = 1
) t
left JOIN (
SELECT Contactid FROM your_table_name
WHERE ruleid <> 2
GROUP BY Contactid
) tt
ON
t.Contactid = tt.Contactid
where tt.Contactid is null
答案 2 :(得分:0)
这样的事情应该有效并且效率很高。
select contactid
from table_name
group by contactid
having min(ruleid) = 2
and max(ruleid) = 2
答案 3 :(得分:0)
这对你来说还不够吗?
select contactid from table group by contactid having count(ruleid)=1