SQL 用于查找在某行上具有所有 ID 的类型
SQL for finding types that have all ids on some row
我在 ACCESS 2010 中使用 SQL 查询,我有一个 table 看起来像这样:
Mytable
ID | TYPE
1 | a
1 | b
2 | a
2 | a
3 | a
3 | b
3 | c
而且我想 return 所有与每个 ID 至少匹配一次的类型。
所以在这种情况下,只有 a
将是 return,因为它是唯一在 1
、2
和 3
行中表示的类型。
不胜感激!
在常规 SQL 中,您可以这样写:
select type
from mytable
group by type
having count(distinct id) = (select count(distinct id) from mytable);
这在 MS Access 中不太适用,因为 Access 不支持 COUNT(DISTINCT)
。
但是,如果我们假设 mytable
中没有重复项,那么这个变体应该有效:
select type
from mytable
group by type
having count(*) = (select count(*)
from (select distinct id from mytable) as t
);
编辑:
如果 table 可能包含重复项,那么您可以在聚合之前删除它们:
select type
from (select distinct type, id from mytable ) as ti
group by type
having count(*) = (select count(*)
from (select distinct id from mytable) as t
);
这是您可以采用的一种方法;子查询 returns 所有至少出现两次的 ID,然后加入这些 ID 存在的所有值。
SELECT a.ID, b.TYPE
FROM
(
SELECT ID
FROM Mytable
GROUP BY ID
HAVING COUNT(ID) > 1
) a
INNER JOIN Mytable b ON b.ID = a.ID
我在 ACCESS 2010 中使用 SQL 查询,我有一个 table 看起来像这样:
Mytable
ID | TYPE
1 | a
1 | b
2 | a
2 | a
3 | a
3 | b
3 | c
而且我想 return 所有与每个 ID 至少匹配一次的类型。
所以在这种情况下,只有 a
将是 return,因为它是唯一在 1
、2
和 3
行中表示的类型。
不胜感激!
在常规 SQL 中,您可以这样写:
select type
from mytable
group by type
having count(distinct id) = (select count(distinct id) from mytable);
这在 MS Access 中不太适用,因为 Access 不支持 COUNT(DISTINCT)
。
但是,如果我们假设 mytable
中没有重复项,那么这个变体应该有效:
select type
from mytable
group by type
having count(*) = (select count(*)
from (select distinct id from mytable) as t
);
编辑:
如果 table 可能包含重复项,那么您可以在聚合之前删除它们:
select type
from (select distinct type, id from mytable ) as ti
group by type
having count(*) = (select count(*)
from (select distinct id from mytable) as t
);
这是您可以采用的一种方法;子查询 returns 所有至少出现两次的 ID,然后加入这些 ID 存在的所有值。
SELECT a.ID, b.TYPE
FROM
(
SELECT ID
FROM Mytable
GROUP BY ID
HAVING COUNT(ID) > 1
) a
INNER JOIN Mytable b ON b.ID = a.ID