问题: 我需要为供应商找到顶级客户。 顶级客户在所有订单上都有最大项目总和。 如果供应商有2个顶级客户,那么顶级客户将使用最小订单ID,这意味着 - 谁首先创建订单并获得最大订单 - 它将是最高的。 我正在写这个sql代码:
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
并获得此结果:http://imageshack.us/photo/my-images/148/32969388.jpg/
答案 0 :(得分:1)
您需要对订单计数和ID进行排名。因此,您应该使用分析和内联视图。类似的东西:
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
/