我似乎无法理解为什么我不能简单地 GROUP BY customer_numb 和 cost_line (使用 sum() 来计算花费的金额)。
当您说group by customer_numb
您知道 customer_numb 唯一标识客户表中的一行时(假设 customer_numb 是主键或备用键),因此任何给定的andcustomers.customer_numb
都只有一个值。但是在解析时,Oracle 不知道,或者至少表现得好像它不知道。它说,有点恐慌,“如果一个单曲有多个值,我该怎么办?”customers.customer_first_name
customers.customer_last_name
customer_numb
customer_first_name
大致规则是,子句中的select
表达式可以使用子句中的表达式group by
和/或使用聚合函数。(以及不依赖于基表的常量和系统变量等)而“使用”我的意思是成为表达式或表达式的一部分。因此,一旦您按名字和姓氏分组,customer_first_name || customer_last_name
这也是一个有效的表达方式。
当您有一个表,例如customers
并按主键分组时,或具有唯一键且非空约束的列时,您可以安全地将它们包含在group by
子句中。在这种特殊情况下,group by customer.customer_numb, customer.customer_first_name, customer.customer_last_name.
另请注意,order by
第一个查询中的 将失败,因为order_lines.cost_line
该组没有单个值。您可以在子句中排序sum(order_lines.cost_line)
或使用列别名并对其排序select
alias
SELECT orders.customer_numb,
sum(order_lines.cost_line),
customers.customer_first_name,
customers.customer_last_name
FROM orders
INNER JOIN customers ON customers.customer_numb = orders.customer_numb
INNER JOIN order_lines ON order_lines.order_numb = orders.order_numb
GROUP BY orders.customer_numb,
customers.customer_first_name,
customers.customer_last_name
ORDER BY sum(order_lines.cost_line)
或者
SELECT orders.customer_numb,
sum(order_lines.cost_line) as sum_cost_line,
. . .
ORDER BY sum_cost_line
注意:我听说一些 RDBMS 将暗示分组的附加表达式,而没有明确说明它们。Oracle 不是这些 RDBMS 之一。
至于按两者分组customer_numb
,cost_line
考虑一个有两个客户的数据库,1 和 2 有两个订单,每个订单:
Customer Number | Cost Line
1 | 20.00
1 | 20.00
2 | 35.00
2 | 30.00
select customer_number, cost_line, sum(cost_line)
FROM ...
group by customer_number, cost_line
order by sum(cost_line) desc
Customer Number | Cost Line | sum(cost_line)
1 | 20.00 | 40.00
2 | 35.00 | 35.00
2 | 30.00 | 30.00
最高的第一行sum(cost_line)
不是花费最多的客户。