SQL Oracle查询。哪个客户名称和号码在10月订购了价格最高的商品?

时间:2015-10-29 16:05:07

标签: sql database oracle-sqldeveloper

哪个客户名称和号码在10月订购了价格最高的商品?

Customer name = account_name [found in table cust_accounts]
customer number = account_number [found in table cust_accounts]
price = unit_selling_price [found in table order_lines_all]
date = creation_date [found in table order_lines_all]

这就是我所拥有的:

select account_name, account_number, max(unit_selling_price)
from cust_accounts ca, order_lines_all ola 
where trunc(ola.creation_date) between '2015-10-01' and '2015-10-30'

我不知道要分组或订购什么。请帮忙。

1 个答案:

答案 0 :(得分:1)

你错过了一个小组:

    select ca.account_name, ca.account_number, ola.max(unit_selling_price) as MaxPrice
    from cust_accounts ca, order_lines_all ola 
    where trunc(ola.creation_date) between '2015-10-01' and '2015-10-30'
and ca.account_number = ola.account_number
    group by account_name, account_number

MaxPrice将自动分组。您需要手动添加其他2。 但即使在那里,如果account_name可以有多个account_number,你最终可能会得到比预期更多的记录。

(我以一种简单的方式加入,但没有让它变得复杂。但它只假设这两个地方都存在这个字段。你必须加入它。)