我无法找到给定查询参数的独占组数据集。
我的表是这样的:
GROUP_ID DOMAIN_ID (unique) -------- --------- 111 2123 111 2124 111 2125 111 2126 112 2124 112 2125 113 2124 113 2125 113 2126 114 2124 114 2127 114 2128
好的,现在我需要找到一个GROUP_ID,其中DOMAIN_ID ONLY 包含 2124 和 2125 ,即它不应该返回111或113上面的例子。
限制:不能使用SP /功能。它应该是一个SQL查询。
非常感谢您提前的时间。
答案 0 :(得分:1)
如果按groupid分组,则可以使用HAVING子句查找min(domainid)= 2124和max(domainid)= 2125
的组答案 1 :(得分:1)
这是一种方法:
SELECT group_id FROM table WHERE group_id IN (SELECT group_id FROM table WHERE domain_id in (2124, 2124)) GROUP BY group_id HAVING count(group_id) = 2;
这种方法的好处是两个domain_ids不需要像其他一个答案那样是顺序的。
在sqlite3中使用您的数据,这会产生:
sqlite> create table t (a int, b int);
sqlite> .import data t
sqlite> SELECT a FROM t WHERE a IN (SELECT a FROM t WHERE b in (2124, 2124)) GROUP BY a HAVING count(a) = 2;
a
112
答案 2 :(得分:1)
你想要得到这样的东西吗?
SELECT DOMAIN_ID, COUNT(*) AS OCCURRENCES FROM TEST WHERE DOMAIN_ID = '2124' OR DOMAIN_ID = '2125' GROUP BY DOMAIN_ID
结果:
DOMAIN_ID OCCURRENCES 2124 4
2125 3
答案 3 :(得分:1)
如果您没有(group_id,domain_id)重复项,则可以使用
SELECT group_id,
SUM(CASE WHEN domain_id=2124 OR domain_id=2125 THEN 1 ELSE -1 END) AS matches
FROM `mytable`
GROUP BY group_id
HAVING matches=2
答案 4 :(得分:1)
SELECT GROUP_ID
FROM atable
GROUP BY GROUP_ID
HAVING COUNT(CASE WHEN DOMAIN_ID IN (2124, 2125) THEN 1 END) = 2
AND COUNT(*) = 2
答案 5 :(得分:1)
感谢大家回答我的问题。
最后,我设法写了一个查询,它给了我想要的结果:
select GROUP_ID
from MY_TABLE oq
where DOMAIN_ID in (2124, 2125)
group by GROUP_ID
having count(GROUP_ID)=2 and
count(GROUP_ID) = (select count(iq.DOMAIN_ID)
from MY_TABLE iq WHERE iq.GROUP_ID=oq.GROUP_ID)
答案 6 :(得分:-1)
SELECT DISTINCT GROUP_ID FROM TABLE
WHERE DOMAIN_ID IN (2124, 2125)
这样的东西?