简体   繁体   中英

How to write a SQL query to get sum of transactions?

I want sql query for this. I have three tables customer,account, transaction the schema of the are as below在此处输入图像描述

I want to get customer details, account id, sum of transaction id在此处输入图像描述

You can Sum the transactions grouped by CustomerID and then join to the customers table on the CustomerID like this:

SELECT c.Customer_name, c.Customer_mobile, t.Transaction_sum
FROM Customer c
JOIN (
    SELECT t.CustomerID, SUM(t.Sum) as Transaction_sum
    FROM transactions t
    GROUP BY t.CustomerID
    ) t on t.CustomerID = c.CustomerID

Your query is quite close. Try this:

SELECT c.customer_id, a.Account_id, SUM(t.transaction_amount) as amount
FROM Account a INNER JOIN
     Customer c
     ON a.customer_id = c.customer_id INNER JOIN
     Transaction t
     ON a.account_id = t.account_id
GROUP BY c.customer_id, a.account_id;

Note the use of table aliases to simplify the query. And -- more importantly -- the SELECT columns and GROUP BY columns are consistent.

Because the customer_id is in the Account table, you don't need the Customer table. So, you can simplify this to:

SELECT a.customer_id, a.Account_id, SUM(t.transaction_amount) as amount
FROM Account a INNER JOIN
     Transaction t
     ON a.account_id = t.account_id
GROUP BY a.customer_id, a.account_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