SQL使用GROUP BY加入两个表

时间:2015-05-21 10:43:48

标签: sql join

我是数据库等世界的新手。开设我店铺的POS的开发人员花了很多钱,不再回答我。我需要将我的应收账款报告为本季度末。请在访问权限中帮助解决此问题。我尝试了左连接,当我只加入购买但没有购买和付款时,它工作正常。

TABLES:

CUSTOMERSTABLE:
CUSTOMERID**********NAME

PURCHASESTABLE:
SALEID**********CUSTOMERID**********AMOUN******TDATE

PAYMENTSTABLE:
PAYMENTSID**********customerid*********amount******TDATE

结果应该显示所有客户(有或没有可用的转换),每个的购买总额,每个的付款总额,未付金额(两个净额),它应该只考虑之前的交易给定的TDATE

1 个答案:

答案 0 :(得分:0)

SELECT cust.customerid, Sum(purch.Amount_charged) AS totalPurchases, Sum(pay.Payment_Made) AS SumOfPayment_Made
FROM (cust INNER JOIN pay ON cust.customerid = pay.Account_Id) INNER JOIN purch ON cust.customerid = purch.Account_Id
WHERE ((([purch].[TDATE]) Between '4/6/2015' And '5/18/2015'))
GROUP BY cust.customerid;