SQL:SQL独家或

时间:2015-12-10 14:51:10

标签: sql oracle xor

我有一张表格:

username | role
---------+------
name1    | internal
name1    | admin
name2    | internal
name3    | admin
name4    | external

我需要找到所有具有“内部”或“管理员”角色的用户,但两者都没有(基本上是异或)。我怎样才能在SQL中执行此操作?

导致表格类似于下面的查询将是完美的:

username | internal | admin
---------+----------+-------
name2    | 1        | 0
name3    | 0        | 1

如果它有助于我使用Oracle数据库

2 个答案:

答案 0 :(得分:6)

我会通过条件聚合来解决这个问题:

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;

如果名称/角色对可以重复,则使用having count(distinct role) = 1

答案 1 :(得分:2)

试试这个

SELECT UserName, 
CASE WHEN Role = 'internal' Then 1 Else 0 END internal,
CASE WHEN Role = 'admin' Then 1 Else 0 END admin
FROM (
SELECT A.*, COUNT(DISTINCT Role) OVER (PARTITION BY UserName) CNT
FROM Users A
) WHERE CNT = 1

SQL FIDDLE