php SUM()子查询,用于查询为每个客户花费的总金额

tkqqtvp1  于 2022-11-28  发布在  PHP
关注(0)|答案(1)|浏览(146)

我遇到了一个问题,我需要帮助。因此,我需要找到每个客户花费的总金额。在数据库中,一个customer_id有多笔付款。下面是我的代码:

"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;");

但是,该列只重复所有客户的总金额。如何解决此问题?

e4yzc0pl

e4yzc0pl1#

此查询的问题如下:

FROM customer, address, city, payment
WHERE customer.address_id = address.address_id
AND address.city_id = city.city_id

您缺少payment表的AND payment.customer_id = customer.id部分。在本例中,数据库联接每个客户的所有付款。因此,当您得到结果时,您得到的是每个客户的所有付款的总和。
注意:AND payment.customer_id = customer.id部分取决于数据库结构。相应地更新payment.customer_idcustomer.id

相关问题