我在MS Access中工作,需要一个SQL解决方案。我有三张桌子:
客户: CustNum (密钥),名称
订单: ID , CustNum ,金额
付款: ID , CustNum ,值
我的问题是编写一个将导致查询的SQL:
CustomerName,TotalOderValue,TotalAmountPaid,BalancePayable 。
我在 CustNum 分组的三个表上尝试了下面的Select
查询,但是它起作用了,但似乎是由于重复行而使得汇总气球。
SELECT CustNum,
Sum(Amount) AS TotalOrderValue,
Sum(Value) AS TotalAmountPaid,
[TotalOrderValue]-[TotalAmoutPaid] AS BalancePayable
FROM (Customers Inner Join Payments ON Customers.CustNum=Payments.CustNum)
INNER JOIN Orders ON Customers.CustNum=Orders.CustNum GROUP BY Customers.CustNum
答案 0 :(得分:0)
基本访问功能。
构建2个聚合查询。然后构建另一个将其连接到Customers表的查询。
如果需要,也可以在第三个查询中嵌套2个聚合查询。使用SQL View将2个聚合查询复制/粘贴到第三个查询中,然后可以删除2个聚合查询对象。这是一体化查询:
SELECT Customers.CustNum, Query1.TotalAmountPaid, Query2.TotalOrderValue, [TotalAmountPaid]-[TotalOrderValue] AS BalancePayable
FROM
(SELECT Payments.CustNum, Sum(Payments.Value) AS TotalOrderValue FROM Payments GROUP BY Payments.CustNum) AS Query2
RIGHT JOIN (
(SELECT Orders.CustNum, Sum(Orders.Amount) AS TotalAmountPaid FROM Orders GROUP BY Orders.CustNum) AS Query1
RIGHT JOIN Customers ON Query1.CustNum = Customers.CustNum) ON Query2.CustNum = Customers.CustNum;