我正在尝试编写一个查询,以显示订单数量以及每个客户在这些订单中购买的商品数量
SELECT customers.customer_id, COUNT(orders.order_id),
SUM(order_details.order_qty)
FROM customers
LEFT OUTER JOIN orders
ON orders.customer_id=customers.customer_id
LEFT OUTER JOIN order_details
ON order_details.order_id=orders.order_id
GROUP BY customers.customer_id;
我要联接三个表,正如到目前为止所写的那样……问题是我的查询结果不正确
customer_id:1个应该有3个订单,n个订单中的项目数量应该是5
我正在使用Oracle数据库12.2.0.1.0
答案 0 :(得分:1)
问题是我的查询结果不正确
猜测您的订单有多个明细记录。因此,只要像这样加入他们,就会根据详细信息记录的数量生成一个产品。
您可以做的是使用内联视图汇总每个订单ID的qty
;
SELECT customers.customer_id
, COUNT(orders.order_id)
, SUM(order_details.tot_qty)
FROM customers
LEFT OUTER JOIN orders
ON orders.customer_id=customers.customer_id
LEFT OUTER JOIN (select order_id, SUM(order_qty) as tot_qty
from order_details
group by order_id) order_details
ON order_details.order_id=orders.order_id
GROUP BY customers.customer_id;