我在Access中构建了一个Union查询,它从两个单独的查询中获取结果并将它们连接在一起。它的工作正常,但结果没有按销售额,成本和利润分组,我试图对这三个字段求和。
这是我的代码:
SELECT
Store,
count( [MASTER CREDIT MEMO QUERY].[Count]) as Count,
[Sales Code],
Name,
Sum( [MASTER CREDIT MEMO QUERY].[Sales]) as Sales,
Sum( [MASTER CREDIT MEMO QUERY].[Cost]) as Cost,
Sum( [MASTER CREDIT MEMO QUERY].[Profit]) as Profit
FROM [MASTER CREDIT MEMO QUERY]
GROUP by
Store,
[Sales Code],
Name
UNION SELECT
Store,
count([MASTER SALES INVOICE QUERY].[Count]) as Count,
[Sales Code],
Name,
Sum([MASTER SALES INVOICE QUERY].[Sales]) as Sales,
Sum([MASTER SALES INVOICE QUERY].[Cost]) as Cost,
Sum([MASTER SALES INVOICE QUERY].[Profit]) as Profit
FROM [MASTER SALES INVOICE QUERY]
GROUP BY
Store,
[Sales Code],
Name
ORDER BY Sales DESC;
有人可以帮我分组工作吗?
答案 0 :(得分:1)
您正在对联合中的单独选择进行分组,而不是联合本身的结果。您应该将组放在整个查询之外,以及组函数。
请尝试这个(我不熟悉ms-access语法,但它应该有效):
SELECT [Store],
count([Count]) as [Count],
[Sales Code],
Name,
Sum( [Sales]) as Sales,
Sum( [Cost]) as Cost,
Sum( [Profit]) as Profit
FROM (SELECT Store, [Count], Sales, Cost, Profit, Name, [Sales Code]
FROM [MASTER CREDIT MEMO QUERY]
UNION
SELECT Store, [Count], Sales, Cost, Profit, Name, [Sales Code]
FROM [MASTER SALES INVOICE QUERY]) t
GROUP BY Store, [Sales Code], Name
ORDER BY Sales DESC
答案 1 :(得分:0)
以下是解决方案,以防您想知道。
非常感谢您的协助。
SELECT TBL1.Store, Count(TBL1.Count) AS [Count], TBL1.[Sales Code], TBL1.Name, Sum(TBL1.Sales) AS Sales, Sum(TBL1.Cost) AS Cost, Sum(TBL1.Profit) AS Profit
FROM (SELECT
Store,
Count,
[MASTER CREDIT MEMO QUERY].Sales,
Cost,
Profit,
Name,
[Sales Code]
FROM [MASTER CREDIT MEMO QUERY]
UNION
SELECT
Store,
Count,
[MASTER SALES INVOICE QUERY].Sales,
Cost,
Profit,
Name,
[Sales Code]
FROM [MASTER SALES INVOICE QUERY]) AS TBL1
GROUP BY TBL1.Store, TBL1.[Sales Code], TBL1.Name
ORDER BY TBL1.Name;