在Access中创建子查询

时间:2015-02-09 20:24:54

标签: ms-access subquery

我正在尝试在Access中创建子查询,但是我收到一条错误,指出此子查询可以返回一条记录。我想找到宠物最多的十大公司,然后我想知道这些宠物的名字。我之前从未创建过子查询,所以我不确定我哪里出错了。这就是我所拥有的:

SELECT TOP 10 dbo_tGovenrnmentRegulatoryAgency.GovernmentRegulatoryAgency
(SELECT dbo_tPet.Pet
FROM dbo_tPet)

FROM dbo_tPet INNER JOIN dbo_tGovenrnmentRegulatoryAgency ON
dbo_tPet.GovernmentRegulatoryAgencyID =
dbo_tGovenrnmentRegulatoryAgency.GovernmentRegulatoryAgencyID
GROUP BY dbo_tGovenrnmentRegulatoryAgency.GovernmentRegulatoryAgency
ORDER BY Count(dbo_tPet.PetID) DESC;

2 个答案:

答案 0 :(得分:1)

考虑这个解决方案,需要WHERE IN ()子句中的子查询:

SELECT t1.GovernmentRegulatoryAgency, dbo_tPet.Pet,
FROM dbo_tPet 
INNER JOIN dbo_tGovenrnmentRegulatoryAgency t1 ON
dbo_tPet.GovernmentRegulatoryAgencyID = t1.GovernmentRegulatoryAgencyID    
WHERE t1.GovernmentRegulatoryAgency IN   
    (SELECT TOP 10 t2.GovernmentRegulatoryAgency
    FROM dbo_tPet 
    INNER JOIN dbo_tGovenrnmentRegulatoryAgency t2 ON
    dbo_tPet.GovernmentRegulatoryAgencyID = t2.GovernmentRegulatoryAgencyID
    GROUP BY t2.GovernmentRegulatoryAgency
    ORDER BY Count(dbo_tPet.Pet) DESC);

不需要表别名,但我将它们包含在演示中。

答案 1 :(得分:0)

希望这样做:

SELECT a.GovernmentRegulatoryAgency, t.NumOfPets
FROM dbo_tGovenrnmentRegulatoryAgency a
INNER JOIN (
    SELECT TOP 10 p.GovernmentRegulatoryAgencyID, COUNT(p.PetID) AS NumOfPets
    FROM dbo_tPet p
    GROUP BY p.GovernmentRegulatoryAgencyID
    ORDER BY COUNT(p.PetID) DESC
) t
ON a.GovernmentRegulatoryAgencyID = t.GovernmentRegulatoryAgencyID

简而言之,首先将嵌套查询排序,确定相关代理商的内容,然后将内部联接返回到代理商表,以获取所选代理机构的详细信息。