[英]How to write a SQL query to get sum of transactions?
您可以对按 CustomerID 分组的交易求和,然后加入 CustomerID 上的客户表,如下所示:
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
您的查询非常接近。 尝试这个:
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;
请注意使用表别名来简化查询。 而且——更重要的是SELECT
列和GROUP BY
列是一致的。
因为customer_id
在Account
表中,所以您不需要Customer
表。 因此,您可以将其简化为:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.