Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: SQL Exclusive Or

Tags:

sql

oracle

xor

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

like image 822
Eduardo Avatar asked Feb 09 '23 08:02

Eduardo


1 Answers

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.

like image 173
Gordon Linoff Avatar answered Feb 11 '23 21:02

Gordon Linoff