I'm having trouble finding exclusive group data set for the given query paramter.
My table is like this:
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
Ok, now I need to find a GROUP_ID where DOMAIN_ID contains and ie it should not return 111 or 113 from the example above. 包含和即它不应该从上面的示例返回111或113。
Limitation: Can't use SP/Function. It should be one SQL query.
Thanks very much for your time in advance.
如果按groupid分组,则可以使用HAVING子句查找min(domainid)= 2124和max(domainid)= 2125的组
Here is one way to do it:
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;
The benefit with this approach is that the two domain_ids don't need to be sequential as in one of the other answers.
Using your data in sqlite3, this produces:
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
Are you trying to get something like this?
SELECT DOMAIN_ID, COUNT(*) AS OCCURRENCES FROM TEST WHERE DOMAIN_ID = '2124' OR DOMAIN_ID = '2125' GROUP BY DOMAIN_ID
results in:
DOMAIN_ID OCCURRENCES 2124 4
2125 3
If you don't have (group_id,domain_id) duplicates you can use
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
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
Thanks everyone for responding to my question.
Finally, I managed to write a query which gives me the result I wanted:
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)
SELECT DISTINCT GROUP_ID FROM TABLE
WHERE DOMAIN_ID IN (2124, 2125)
Something like this?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.