[英]SUM() subquery for total money spent for each customer
I'm stuck on a problem and I need help.我遇到了一个问题,需要帮助。 So, I need to find the total money spent per customer.
所以,我需要找出每个客户花费的总金额。 In the database, one customer_id has multiple payments.
在数据库中,一个customer_id 有多个付款。 This is my code:
这是我的代码:
"SELECT customer.first_name, customer.last_name, customer.customer_id, address.address, city.city, address.postal_code, SUM(amount) as money_spent
FROM customer, address, city, payment
WHERE customer.address_id = address.address_id
AND address.city_id = city.city_id
GROUP BY customer_id
ORDER BY customer.last_name ASC;");
However, that column only repeats the total amount for all customers.但是,该列仅重复所有客户的总金额。 How to fix this?
如何解决这个问题?
The problem with this query is here:此查询的问题在于:
FROM customer, address, city, payment
WHERE customer.address_id = address.address_id
AND address.city_id = city.city_id
You're missing the AND payment.customer_id = customer.id
part for the payment
table.您缺少
payment
表的AND payment.customer_id = customer.id
部分。 In this case, the database joins all payments for each customer.在这种情况下,数据库会加入每个客户的所有付款。 So when you get the result, you're getting the total sum for all payments with each customer.
因此,当您获得结果时,您将获得每个客户的所有付款的总金额。
Note: the AND payment.customer_id = customer.id
part depends on the database structure.注意:
AND payment.customer_id = customer.id
部分取决于数据库结构。 Update payment.customer_id
and customer.id
accordingly.相应地更新
payment.customer_id
和customer.id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.