Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 按多个条目筛选查询结果_Sql_Ms Access - Fatal编程技术网

Sql 按多个条目筛选查询结果

Sql 按多个条目筛选查询结果,sql,ms-access,Sql,Ms Access,我有一个Access DB,表1包含以下信息: ADDRESS_ID | CATEGORY_ID 1 | 12 2 | 41 2 | 66 3 | 41 4 | 41 4 | 66 每个地址_ID属于唯一分配的专用客户 我需要创建一个SQL查询,该查询只返回表中地址ID正好有一个专用条目的行,例如,如果我的筛选条件是Return CATEGORY_ID=41,则预期结果是: ADDRES

我有一个Access DB,表1包含以下信息:

ADDRESS_ID | CATEGORY_ID
1          | 12
2          | 41
2          | 66
3          | 41
4          | 41
4          | 66
每个地址_ID属于唯一分配的专用客户

我需要创建一个SQL查询,该查询只返回表中地址ID正好有一个专用条目的行,例如,如果我的筛选条件是Return CATEGORY_ID=41,则预期结果是:

ADDRESS_ID | CATEGORY_ID
3          | 41
或者,如果它是返回类别_ID=66,则结果为空表

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

使用计数并具有:

我将使用不存在的:

此查询:

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

仅表中地址_ID正好有一行的行 专用入口

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

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
我将使用group by,并拥有:

如果需要,您可以将41作为类别id添加到选择中,但您已经知道了这一点

如果表中没有重复对,您也可以将其表述为:

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

工作完美。谢谢
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
select address_id
from table1
group by address_id
having min(category_id) = max(category_id) and
       min(category_id) = 41;
select address_id
from table1
group by address_id
having count(*) = 1 and
       min(category_id) = 41;