按多个条目过滤查询结果

时间:2019-04-09 14:43:24

标签: sql ms-access

我有一个带有表Table1的Access DB,该表包含以下信息:

ADDRESS_ID | CATEGORY_ID
1          | 12
2          | 41
2          | 66
3          | 41
4          | 41
4          | 66

每个ADDRESS_ID都属于一个专用客户(唯一分配)。

我需要创建一个SQL查询,该查询仅返回表中那些ADDRESS_ID恰好具有一个专用条目的行,例如如果我的过滤条件是“返回CATEGORY_ID = 41”,则预期结果是:

ADDRESS_ID | CATEGORY_ID
3          | 41

或者如果它是“ Return CATEGORY_ID = 66”,则结果为空表。

如何在不通过脚本执行后处理的情况下实现查询?

4 个答案:

答案 0 :(得分:1)

我将使用group byhaving

select address_id
from table1
group by address_id
having min(category_id) = max(category_id) and
       min(category_id) = 41;

如果需要,可以将41 as category_id添加到select,但是您已经知道了。

如果表中没有重复的对,则也可以将其表达为:

select address_id
from table1
group by address_id
having count(*) = 1 and
       min(category_id) = 41;

答案 1 :(得分:0)

使用build.gradlecount()

having

答案 2 :(得分:0)

我会使用NOT EXISTS

select t.*
from table as t
where CATEGORY_ID = 66 and
      not exists (select 1 
                  from table as t1 
                  where t1.ADDRESS_ID = t.ADDRESS_ID and t1.CATEGORY_ID <> t.CATEGORY_ID
                 );

答案 3 :(得分:0)

此查询:

select address_id, max(category_id) category_id
from tablename
group by address_id
having min(category_id) = max(category_id)

返回:

  

仅表中ADDRESS_ID恰好为1的那些行   专用条目

现在,您可以对其应用任何过滤器并获得所需的结果:

select t.* from (
    select address_id, max(category_id) category_id
    from tablename
    group by address_id
    having min(category_id) = max(category_id)
) t
where t.category_id = 41