Suppose I have the following tables
"AGENT-DIVISION"
DIVISION_ID AGENT_ID
102 1
104 1
102 50
4 100
"AGENT-ROLE"
ROLE_ID AGENT_ID
2 1
4 1
2 50
4 50
4 100
I would like to obtain all the divisions that have roles 2 and 4, in this example it would return the divisions with id 102 and 104
I have tried these queries:
select division_id, ar.role_id from agent_division d
INNER JOIN agent a on d.agent_id = a.id
inner join agent_role ar on ar.agent_id = a.id and ar.role_id in (2,4)
group by division_id, ar.role_id
having count(distinct ar.role_id) = 2;
select d.division_id, ar.role_id from agent_division d, agent a, agent_role ar
where d.agent_id = a.id and ar.agent_id = a.id and ar.role_id in (2,4)
group by d.division_id, ar.role_id having count(distinct ar.role_id) = 2;
Any suggestion?
What you can do is group by
agent_id
and show only the ones that have two roles:Integrated to the query of
agent_division
, you could be:As you only mention 2
ROLE_ID
of your interest; I suggest the following:We apply to the "view" created in
WITH
which it returns those repeated more than once (although the correct thing would be to explicitly put equal to 2), but just so that it serves as a guide there.