查询不包括指定的表达式作为UNION查询中的聚合函数的一部分

时间:2016-04-13 13:47:52

标签: sql ms-access aggregate-functions

我正在进行联合查询,将两个不同查询的结果加在一起,这些查询为我提供了来自两个不同会计期间的数据,以获得滚动的12个月数字。 我收到消息“您的查询不包含指定的表达式”Report_Header“作为聚合函数的一部分”。我已经读过该字段需要在最后包含在GROUP BY语句中,但是当我从任一查询或两个查询添加字段时如下所示,我仍然得到消息。救命?我不是程序员,我是Access用户,所以我需要简单请:)。

SELECT [JOIN_IB_FREIGHT&PURCHASES_ROLLING12_SUB].Report_Header,
       Sum([JOIN_IB_FREIGHT&PURCHASES_ROLLING12_SUB].SumOfCASES) AS CASES,
       Sum([JOIN_IB_FREIGHT&PURCHASES_ROLLING12_SUB].SumOfPurchases) AS PURCHASES
FROM [JOIN_IB_FREIGHT&PURCHASES_ROLLING12_SUB]

UNION ALL

SELECT [JOIN_IB_FREIGHT&PURCHASES_Rolling12_SUB2].Report_Header,
       Sum([JOIN_IB_FREIGHT&PURCHASES_Rolling12_SUB2].SumOfCASES) AS CASES,
       Sum([JOIN_IB_FREIGHT&PURCHASES_Rolling12_SUB2].SumOfPurchases) AS PURCHASES
FROM [JOIN_IB_FREIGHT&PURCHASES_Rolling12_SUB2]
GROUP BY [JOIN_IB_FREIGHT&PURCHASES_ROLLING12_SUB].Report_Header,
         [JOIN_IB_FREIGHT&PURCHASES_Rolling12_SUB2].Report_Header

谢谢!

2 个答案:

答案 0 :(得分:0)

GROUP BY [JOIN_IB_FREIGHT&PURCHASES_ROLLING12_SUB].Report_Header放在第一个查询下而不是第二个查询。

答案 1 :(得分:0)

您可以聚合两个子查询:

SELECT [JOIN_IB_FREIGHT&PURCHASES_ROLLING12_SUB].Report_Header,
       Sum([JOIN_IB_FREIGHT&PURCHASES_ROLLING12_SUB].SumOfCASES) AS CASES,
       Sum([JOIN_IB_FREIGHT&PURCHASES_ROLLING12_SUB].SumOfPurchases) AS PURCHASES
FROM [JOIN_IB_FREIGHT&PURCHASES_ROLLING12_SUB]
GROUP BY [JOIN_IB_FREIGHT&PURCHASES_Rolling12_SUB].Report_Header

UNION ALL

SELECT [JOIN_IB_FREIGHT&PURCHASES_Rolling12_SUB2].Report_Header,
       Sum([JOIN_IB_FREIGHT&PURCHASES_Rolling12_SUB2].SumOfCASES) AS CASES,
       Sum([JOIN_IB_FREIGHT&PURCHASES_Rolling12_SUB2].SumOfPurchases) AS PURCHASES
FROM [JOIN_IB_FREIGHT&PURCHASES_Rolling12_SUB2]
GROUP BY [JOIN_IB_FREIGHT&PURCHASES_Rolling12_SUB2].Report_Header;

这可能就是你想要的。但是,它不会将两个表中相同标题下的信息组合在一起。为此,最简单的方法可能是一种观点。