在表格中找到一组值,该值根据两个不同的标准比较计数并匹配计数[ms-access]

时间:2018-11-23 21:04:49

标签: ms-access

我有一张桌子:

TEST1

+-------+----------+-------------+--------+
| AppID | Platform |  Category   | Status |
+-------+----------+-------------+--------+
|  1234 | AA       | Application | ON     |
|  1234 | BB       | WAN         | OFF    |
|  1234 | CC       | Application | ON     |
|  2222 | DD       | Application | OFF    |
|  2222 | EE       | WAN         | OFF    |
|  2222 | FF       | Application | ON     |
+-------+----------+-------------+--------+

我想找到所有带有Category = 'Application'的AppID,以及 ALL 带有Status = 'ON'的行。在上面的示例中,AppID 1234符合该条件。

我尝试使用以下查询,但未返回任何结果。 (正确的结果应该只是AppID:1234)。

有什么建议吗?

SELECT AppID
FROM TEST1
WHERE Category = "Application" 
GROUP BY AppID
HAVING 
Count(AppID) = (Select count(AppID) from TEST1 WHERE Category="Application" AND Status="ON")

1 个答案:

答案 0 :(得分:0)

我建议以下内容:

select t.appid
from test1 t
where t.category = 'Application'
group by t.appid
having min(t.status) = max(t.status) and min(t.status) = 'ON'

或者,或者使用相关子查询:

select distinct t.appid
from test1 t
where t.category = 'Application' and not exists
(
    select 1 
    from test1 u 
    where u.appid = t.appid and u.category = 'Application' and u.status <> 'ON'
)

或使用联接的子查询:

select distinct t.appid
from test1 t left join 
(
    select u.appid 
    from test1 u 
    where u.category = 'Application' and u.status <> 'ON'
) v 
on t.appid = v.appid
where t.category = 'Application' and v.appid is null