我正在使用Oracle 11g Application Express,并在SQL Plus CLI中执行这些命令。这是一堂课,我无法解决这个问题。我不知道如何在订单上添加项目的总数量 - 我感到困惑,因为我不知道如何根据ORDER获取QUANTITY的总和(客户有多个订单)。
对于每个有订单的客户,列出客户编号,订单数量 客户拥有的,这些订单上的商品总数以及总价 这几项。按客户编号订购输出。 (提示:您必须使用GROUP BY 此查询中的子句)。
表格(我们将使用):
客户:包含customer_num
ORDERS:包含order_num,customer_num
项目:包含order_num,quantity,total_price
我的逻辑:我需要能够计算每个客户的每个订单数量的总和。我在这里待了一个多小时,无法理解。
到目前为止,这是我可以制定的......
SELECT customer_num, count(customer_num)
FROM orders
GROUP BY customer_num;
我不太了解如何GROUP BY(是的,我已经谷歌搜索并研究了一下,它只是没有点击),我不知道怎么采取SUM每个客户每个订单的QUANTITY。
没有找人为我做我的工作,只是一些指导 - 谢谢!
答案 0 :(得分:1)
select o.customer_num,
count(distinct o.order_num) as num_orders,
sum(i.quantity) as total_qty,
sum(i.total_price) as total_price
from orders o
join items i
on o.order_num = i.order_num
group by o.customer_num
order by o.customer_num
第一件事: 你必须加入解决问题所需的两个表(订单和项目)。相关字段似乎是order_num
第二件事: 你的group by子句没问题,你想要每个客户一行。但由于连接到项目表,您将需要计算DISTINCT订单(因为订单和项目之间可能存在一对多的关系)。否则,包含2个不同关联项目的订单将被计算两次。
接下来,总结数量和总价格,您现在可以这样做,因为您已加入所需的表格。
答案 1 :(得分:1)
使用WHERE
:
SELECT orders.customer_num, /*customer number*/
COUNT(DISTINCT orders.order_num) AS "num_orders", /*number of orders/c*/
SUM(items.quantity) as "total_qty", /*total quantity/c*/
SUM(items.total_price) as "total_price" /*total price/items*/
/* For each customer having an order, list the customer number,
the number of orders that customer has, the total quantity of items
on those orders, and the total price for the items.
Order the output by customer number.
(Hint: You must use a GROUP BY clause in this query). */
FROM orders, items
WHERE orders.order_num = items.order_num
GROUP BY orders.customer_num
ORDER BY orders.customer_num
;