SQL Union Query - 两个访问表

Posted

技术标签:

【中文标题】SQL Union Query - 两个访问表【英文标题】:SQL Union Query - two access tables 【发布时间】:2019-03-06 09:14:02 【问题描述】:

我在 MS Access 中有两个相同的查询,qryLabourqryMaterials。我需要从三个字段中获取总数:Labour MinsLaser Mins$ Cost

我知道这可以使用联合查询来完成,但我已经很久没有使用联合查询了,而且我不断收到“FROM 语句错误”。

我的 SQL 是:

SELECT sum(TotalLabour) as TotalLabour,sum(TotalCost) as TotalCost,sum(TotalLaser) as TotalLaser
FROM

(
SELECT Sum([qryLabour].[Labour Mins]) AS TotalLabour, Sum([qryLabour].[$ Cost]) AS TotalCost, Sum([qryLabour].[Laser Mins]) AS TotalLaser
FROM qryLabour;

union all

SELECT Sum([qryMaterial].[Labour Mins]) AS TotalLabour, Sum([qryMaterial].[$ Cost]) AS TotalCost, Sum([qryMaterial].[Laser Mins]) AS TotalLaser
FROM qryMaterial;

)

请有人告诉我哪里出错了?如果我删除***“选择”语句,我会得到两行,其中包含总计,这是我添加***语句以合并两者的时候。

【问题讨论】:

可能通过将别名放在右括号中将解决问题) M 但不确定 删除那些分号。 (;) 【参考方案1】:

请注意,但我认为您需要一个别名:

SELECT sum(u.TotalLabour) as TotalLabour,sum(u.TotalCost) as TotalCost,sum(u.TotalLaser) as TotalLaser
FROM

(
SELECT Sum([qryLabour].[Labour Mins]) AS TotalLabour, Sum([qryLabour].[$ Cost]) AS TotalCost, Sum([qryLabour].[Laser Mins]) AS TotalLaser
FROM qryLabour

union all

SELECT Sum([qryMaterial].[Labour Mins]) AS TotalLabour, Sum([qryMaterial].[$ Cost]) AS TotalCost, Sum([qryMaterial].[Laser Mins]) AS TotalLaser
FROM qryMaterial

) as u

编辑:同时删除“;”在子查询中,正如@jarlh 建议的那样

【讨论】:

【参考方案2】:

谢谢杰迪普。

我实际上只是想通了,我在内部 SELECT 语句的末尾有 ;,我删除了它,并使父 SELECT 中的名称唯一。现在工作得很好。

所以正确的代码是:

SELECT sum( tempTotalLabour) as TotalLabour,sum( tempTotalCost) as TotalCost,sum( tempTotalLaser) as TotalLaser
FROM

(
SELECT Sum([qryLabour].[Labour Mins]) AS tempTotalLabour, Sum([qryLabour].[$ Cost]) AS  tempTotalCost, Sum([qryLabour].[Laser Mins]) AS tempTotalLaser
FROM qryLabour

union all

SELECT Sum([qryMaterial].[Labour Mins]) AS  tempTotalLabour, Sum([qryMaterial].[$ Cost]) AS  tempTotalCost, Sum([qryMaterial].[Laser Mins]) AS  tempTotalLaser
FROM qryMaterial

) ;

干杯 克里斯

【讨论】:

以上是关于SQL Union Query - 两个访问表的主要内容,如果未能解决你的问题,请参考以下文章

第八十章 SQL命令 UNION

sql语句里面的union是啥意思

如何用union合并SQL查询的数据

sql 用union合并合并查询结果

使用 UNION ALL SQL 查询获取更多值

SQL UNION - 添加源