我有以下查询
SELECT
SUM(order_total),
CONCAT_WS(" ", `first_name`, `last_name`) AS `Customer Name`,
COUNT(order_id)
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id
求和不正确,我需要对每个客户的总数求和
请告知。
答案 0 :(得分:0)
您错过了GROUP BY
。如果您不添加它(并在列的一部分中使用SUM
或COUNT
之类的聚合函数),MySQL会将所有行分组为一个结果。它不可能神奇地知道您想知道每个客户的结果,因此您必须明确地告诉它。
SELECT
SUM(order_total),
CONCAT_WS(" ", first_name, last_name) AS Customer Name,
COUNT(order_id)
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id
GROUP BY customers.customer_id