对于我的mySQL课程,我们正在创建一个管理客户订单的数据库。其中一个问题是要求我列出所有客户和每位客户的总收入。
我的问题是,有些订单已经订购了多个相同的商品,因此当我将数量引入SUM时,任何订购单个商品的订单的订单都被错误地总结,但我不知道如何解决这个问题。
这是我现在的代码:
SELECT customers.customer_name, customers.customer_id,
SUM(items.retail_price*orderline.order_qty) AS 'Total Retail Price'
FROM customers
INNER JOIN orders on customers.customer_id = orders.customer_id
INNER JOIN orderline on orders.order_id = orderline.order_id
INNER JOIN items on orderline.item_id = items.item_id
GROUP BY customers.customer_name;
我意识到它有点混乱,所以任何关于清理它的建议都会受到赞赏;我现在只与mySQL合作了大约一个月,所以它对我来说还是新的。
提前致谢!
示例数据:
item_id: 300, unit_cost: 156.00, order_qty: 2
item_id: 600, unit_cost: 92.00, order_qty: 2
item_id: 450, unit_cost: 79.98, order_qty: 6
item_id: 600, unit_cost: 92.00, order_qty: 8
item_id: 200, unit_cost: 241.98, order_qty: 4
如果我做了正确的数学运算,我应该得到2,727.80
,但我对此客户的输出列为2,679.80
。
答案 0 :(得分:0)
SELECT distinct c.customer_id, c.customer_name, sum(ol.order_qty * i.retail_price) as total FROM `customers` as c
left join orders as o ON c.customer_id = o.customer_id
left join orderline as ol ON o.order_id = ol.order_id
left join items as i on i.item_id = ol.item_id
where c.customer_id = 2200
计算结果为2679.80
答案 1 :(得分:0)
我用另一个逻辑重写了查询,结果如下:
我的查询:
SELECT c.customer_name, c.customer_id, SUM(o_price.total) as 'Total Retail Price'
FROM customers c JOIN orders o
ON c.customer_id = o.customer_id
JOIN
(
SELECT
order_id,
SUM(i.retail_price * ol.order_qty) as 'total'
FROM
orderline ol
JOIN items i ON ol.item_id = i.item_id
GROUP BY
ol.order_id
) o_price
ON o.order_id = o_price.order_id
GROUP BY c.customer_id
ORDER BY c.customer_id;
我的结果集
Cora Blanca 1000 280.80
Yash Reed 1100 1723.88
John Mills 1200 363.24
Tina Evans 1400 4974.32
Will Allen 1500 1444.00
James Boyd 1600 173.58
Ann Damian 1900 271.24
Jane Brown 2100 1213.52
Betty Draper 2200 2679.80
您的结果集:
Cora Blanca 1000 280.80
Yash Reed 1100 1723.88
John Mills 1200 363.24
Tina Evans 1400 4974.32
Will Allen 1500 1444.00
James Boyd 1600 173.58
Ann Damian 1900 271.24
Jane Brown 2100 1213.52
Betty Draper 2200 2679.80
<强>结论:强>
两个结果完全相同。您的查询绝对精确且写得很好。现在你有2个查询用于相同的目的,应用最好的一个:)