[英]comparing data from tables in sql server
I am facing great peril. 我面临着巨大的危险。 I have 2 TABLES--- purchaseTbl and CustomerTbl , which contain: 我有2个表--- PurchaseTbl和CustomerTbl,其中包含:
purchaseTbl : C_ID (int - FK) , Purchase_amt (int) PurchaseTbl:C_ID(int-FK),Purchase_amt(int)
CustomerTbl: C_ID (int - PK), [other details]. CustomerTbl:C_ID(int-PK),[其他详细信息]。
So i want to calculate the sum of all purchases where the C_ID in both the tables match 所以我想计算两个表中的C_ID匹配的所有购买的总和
Thank you 谢谢
Gru 格鲁
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
If you just want to know the total amount and not split it into customers then: 如果您只想知道总金额而不将其分成客户,那么:
SELECT SUM(Purchase_amt) AS SUMP
FROM CustomerTbl C
JOIN purchaseTbl P
ON P.C_ID = C.C_ID
The above will get the total amount only if there is a corresponding C_ID
in CustomerTbl
. 仅当CustomerTbl
有相应的C_ID
,以上内容才会获得总额。
像这样在查询中使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.