简体   繁体   中英

comparing data from tables in sql server

I am facing great peril. I have 2 TABLES--- purchaseTbl and CustomerTbl , which contain:

purchaseTbl : C_ID (int - FK) , Purchase_amt (int)

CustomerTbl: C_ID (int - PK), [other details].

So i want to calculate the sum of all purchases where the C_ID in both the tables match

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 .

像这样在查询中使用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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM