SQL联合查询-两个访问表

时间:2019-03-06 09:14:02

标签: sql ms-access union union-all

我在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;

)

请有人能告诉我我要去哪里错了吗?如果删除顶层的“选择”语句,我将得到两行包含总计的行,这是我添加顶层语句来合并两者的时候。

2 个答案:

答案 0 :(得分:2)

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

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建议

答案 1 :(得分:0)

感谢Jaydip。

我实际上才知道,在内部;语句的末尾有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

) ;

欢呼 克里斯