简体   繁体   中英

Group by ID, only where another column has the same value

I want to GROUP BY CAT_ID, but only show results WHERE GROUP_ID is only = 1. If it has 1 and other values for that unique CAT_ID, I don't want to include it.

GROUP_ID  CAT_ID
1         1 
1         1
1         1
2         1
3         1
3         1
1         2
1         2
1         3
2         3

So in this case the results would be:

CAT_ID
2

Since CAT_ID 2 is the only grouping where GROUP_ID is all 1.

Use group by and having :

select cat_id
from t
group by cat_id
having max(group_id) = 1;

The above answers your question because you are looking for the minimum group_id . A more general solution is:

having min(group_id) = max(group_id) and max(group_id) = 1;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM