oracle的初始情况(子查询的东西)

时间:2013-05-19 15:50:32

标签: sql oracle sum subquery

对于Oracle, 从这些表中,

表1 CUSTOMER : has cust_fname, cust_lname, cust_id

表2 SALESORDER : has so_number, so_custid

表3 ITEM : has item_qty, item_sonum

while CUST_ID = SO_CUSTID and SO_NUMBER = ITEM_SONUM (FK relationship)

我想用全名显示客户名称(表示cust_fname + cust_lname),而这个客户(只有一个)是订购了最多项目的人(意味着必须对item_qty做一些事情)。

如何为此任务编写代码?

谢谢

1 个答案:

答案 0 :(得分:1)

尝试

select cust_fname, cust_lname
from
(select c.cust_fname, c.cust_lname
from customer c join salesorder so on so.so_custid = c.cust_id
join ITEM i on i.item_sonum = so.so_number
group by c.cust_fname, cust_lname
order by sum(i.item_qty) desc)
where rownum = 1

Here is a sqlfiddle demo

select cust_fname, cust_lname
from
(select c.cust_fname, c.cust_lname, rank() over (order by sum(i.item_qty) desc) rnk
from customer c join salesorder so on so.so_custid = c.cust_id
join ITEM i on i.item_sonum = so.so_number
group by c.cust_fname, cust_lname
)
where rnk = 1;