在Access中组合多个查询,以便在单个表中的不同字段中显示数据

时间:2014-04-29 17:18:12

标签: sql ms-access ms-access-2010

我有两个想要加入的查询。 Union选项不起作用,因为我希望值显示在不同的字段中。第一个查询是

 SELECT Outage.DISTRICT, Count(Outage.DISTRICT) AS CountOfDISTRICT
 FROM Outage LEFT JOIN [Site ID gets generated] ON Outage.[Site ID]=[Site ID gets     generated].[Site ID]
 GROUP BY Outage.DISTRICT;

第二个查询是

SELECT Outage.DISTRICT, Count(Outage.[Site ID]) AS [CountOfSite ID]
FROM Outage
GROUP BY Outage.DISTRICT;

我尝试了下面的代码但它在第一个查询中给出了语法错误(缺少运算符)

SELECT Outage.DISTRICT,
(SELECT  Count(Outage.[Site ID]) AS [CountOfSite ID] FROM Outage),
(SELECT  Count(Outage.DISTRICT) AS CountOfDISTRICT FROM Outage LEFT JOIN [Site ID gets generated] ON Outage.[Site ID]=[Site ID gets generated].[Site ID])
GROUP BY Outage.DISTRICT;

如果回答也给出了解释,那将是非常有帮助的,因为我是一个很新的访问并试图从头开始学习它。

1 个答案:

答案 0 :(得分:1)

您可以将两个查询连接在一起以并排显示其列:

select
  sq1.DISTRICT
, sq1.CountOfDISTRICT
, sq2.[CountOfSite ID]
from (
  ... your first query here ...
) as sq1
inner join (
  ... your second query here ...
) as sq2
on sq1.DISTRICT = sq2.DISTRICT

要记住的是,联合用于垂直连接表/查询,而连接用于水平连接它们。