如何编写SQL查询以获取交易金额?

时间:2020-07-14 13:42:45

标签: mysql sql sql-server

我想要对此进行sql查询。我有三个表客户,账户,交易 的架构如下enter image description here

我想获取客户详细信息,帐户ID,交易ID之和enter image description here

2 个答案:

答案 0 :(得分:0)

您可以对按客户ID分组的交易进行求和,然后像这样在客户ID上加入客户表:

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

答案 1 :(得分:0)

您的查询非常接近。试试这个:

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_idAccount表中,因此不需要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;