I have a table in the form:
username | role
---------+------
name1 | internal
name1 | admin
name2 | internal
name3 | admin
name4 | external
I need to find all users that have the role either 'internal or 'admin' but don't have both (essentially an XOR). How can I do this in SQL?
A query that results in a form similar to below would be perfect:
username | internal | admin
---------+----------+-------
name2 | 1 | 0
name3 | 0 | 1
If it helps I'm using an Oracle database
I would approach this with conditional aggregation:
select username,
max(case when role = 'internal' then 1 else 0 end) as internal,
max(case when role = 'admin' then 1 else 0 end) as admin
from t
where role in ('internal', 'admin')
group by username
having count(*) = 1;
If name/role pairs could be duplicated, then use having count(distinct role) = 1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With