我面临着极大的危险。 我有2个表--- purchaseTbl和CustomerTbl,其中包含:
purchaseTbl:C_ID(int - FK),Purchase_amt(int)
CustomerTbl:C_ID(int - PK),[其他详细信息]。
所以我想计算两个表中C_ID匹配的所有购买总和
谢谢
格吕
答案 0 :(得分:0)
SELECT C.C_ID,
--You can add more columns (like customer name) here if you wish
SUM(Purchase_amt) AS SUMP
FROM CustomerTbl C
JOIN purchaseTbl P
ON P.C_ID = C.C_ID
GROUP BY C.C_ID
--If you added more columns in the select add them here too separated with comma
如果您只是想知道总金额而不是将其分成客户,那么:
SELECT SUM(Purchase_amt) AS SUMP
FROM CustomerTbl C
JOIN purchaseTbl P
ON P.C_ID = C.C_ID
只有C_ID
中有相应的CustomerTbl
时,上述内容才能获得总金额。
答案 1 :(得分:0)
在您的查询中使用group by子句,就像这样....
SELECT CustomerTbl.C_ID, SUM(Purchase_amt) AS PurchaseSUM FROM CustomerTbl, purchaseTbl WHERE purchaseTbl.C_ID = CustomerTbl.C_ID GROUP BY CustomerTbl.C_ID