问题
For Oracle, From these tables,
Table 1 CUSTOMER : has cust_fname, cust_lname, cust_id
Table 2 SALESORDER : has so_number, so_custid
Table 3 ITEM : has item_qty, item_sonum
while CUST_ID = SO_CUSTID and SO_NUMBER = ITEM_SONUM (FK relationship)
I want to show customer name with full name (means cust_fname+cust_lname) whereas this customer (just one) is the one who had ordered the highest numbers of items (means has to do something with item_qty).
How can I write a code for this task?
Thank you
回答1:
Try
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;
来源:https://stackoverflow.com/questions/16636487/inception-situation-with-oracle-sub-query-stuffs