SQL 查找具有所选 属性 值的行

SQL to find rows with selected property values

我有一个数据库视图,结果如下:

据此我想 select 所有具有组 00113 和 00221 的用户..等等。那是有权访问所有这些组而不是任何一个组的用户。

select * from table 
where ID not IN 
( select distinct ID from Table
   where GROUP_NUMBER not IN ('00221','00113') 
) group by ID having count (distinct GROUP_NUMBER) = 2;

正如 ruudvan 指出的那样,这可以直接用一个 IN

 select * from table 
 where ID IN ('00221','00113') 
 group by ID having count (distinct GROUP_NUMBER) = 2;

内部查询给出了所有 group_number 不在给定列表中的 ID 的列表。
因此,您需要 select 内部查询给出的 ID 中不存在的所有 ID

select first_name, last_name, id from mytable where group_number = '00113'
INTERSECT
select first_name, last_name, id from mytable where group_number = '00221'

你的意图有点模棱两可,但如果你想要的是 return 例如可以访问组 0011300221 而没有其他组的用户,那么这个会工作。

一种方法是在组的 having 子句中使用条件聚合:

select id from your_table
group by id
having sum(case 
    when group_number = '00113' then 1
    when group_number = '00221' then 1 
    else -1 end
    ) = 2

Sample SQL Fiddle

我喜欢使用 group byhaving 进行这些类型的查询。在列表中查找内容的一种方法:

select id
from table
where group_number in ('00113', '00221')
group by id
having count(distinct group_number = '00113') = 2;

一种更通用的方法,允许您获取一个列表的成员,排除另一个列表的成员:

select id
from table
group by id
having sum(case when group_number = '00113' then 1 else 0 end) > 0 and
       sum(case when group_number = '00221' then 1 else 0 end) > 0;