How to select multiple columns without duplicates in one column in Oracle
The problem: I need find top client for supplier. Top client has max items sum on all orders. If supplier has 2 top clients, then top client will be with min order id, which means - who first created order and get max items - it will be top. I was writing this sql code:
select s.s_id, c.c_id, min(o.o_id), count(*)
from suppliers s, clients c, orders o, items i
where s.s_id=c.id_s and c.c_id=o.id_c and o.o_id=i.id_o
group by s.s_id, c.c_id
order by 4 desc, 3
and get this result: http://imageshack.us/photo/my-images/148/32969388.jpg/
but i need to 开发者_如何学编程get: http://imageshack.us/photo/my-images/842/51815927.jpg/
You need to rank the order count and ID. So you should use an analytic and inline views. Something like:
select s_id
, c_id
, min_order_id
, no_of_orders
from (
select s_id
, c_id
, min_order_id
, no_of_orders
, rank() over (partition by s_id
order by no_of_orders DESC, min_order_id ASC) rnk
from (
select s.s_id
, c.c_id
, min(o.o_id) as min_order_id
, count(*) as no_of_orders
from suppliers s, clients c, orders o, items i
where s.s_id=c.id_s and c.c_id=o.id_c and o.o_id=i.id_o
group by s.s_id, c.c_id
)
)
where rnk=1
/
精彩评论