我是一名新手程序员,对SQL的知识非常有限。我已经尝试了几个小时,已经阅读了我能找到的所有资源,但似乎无法解决如何加入这两个表并使用ACCESS数据库获取总发票金额。
TblInvoices
CustomerID
InvoiceAmount
TblCustomers
CustomerID
CustomerName
CustomerRep
我需要的只是客户名称,他们的代表和他们的发票的总价值(确定在某些日期之间,但我已经破解了这一点)。我已经尝试了内连接和其他任何我能找到的但没有太多运气的东西。
作为一个想法...
"SELECT CustomerName, CustomerRep, Sum(InvoiceAmount) AS INVOICETOTAL
FROM TblCustomers, TblInvoices WHERE TblCustomers.CustomerID = TblInvoices.CustomerID
GROUP BY CustomerID"
感谢任何帮助。
答案 0 :(得分:1)
您当前的查询已结束,但由于您在SELECT中有CustomerName
和CustomerRep
,因此您需要GROUP BY
这些列:
SELECT TblCustomers.CustomerName,
TblCustomers.CustomerRep,
Sum(TblInvoices.InvoiceAmount) AS INVOICETOTAL
FROM TblCustomers
INNER JOIN TblInvoices
ON TblCustomers.CustomerID = TblInvoices.CustomerID
GROUP BY TblCustomers.CustomerName, TblCustomers.CustomerRep;
MS Access要求在使用聚合时,SELECT列表中出现的任何列都包含在聚合函数或GROUP BY
子句中。如果您只想GROUP BY
CustomerId
,那么您还可以使用子查询来获得结果:
SELECT c.CustomerName,
c.CustomerRep,
i.INVOICETOTAL
FROM TblCustomers c
INNER JOIN
(
SELECT Sum(InvoiceAmount) AS INVOICETOTAL,
CustomerID
FROM TblInvoices
GROUP BY CustomerID
) i
ON TblCustomers.CustomerID = i.CustomerID