等级函数与总和

时间:2016-02-28 21:10:15

标签: sql-server oracle sum rank

我有两张桌子。

abc(CID(pk), cname,)
order(order_id(pk), CID(fk), number_of_rentals)

我想根据他们租用的电影数量确定前10名客户。

select 
    orders.cid,orders.no_rentals, abc.name, 
    rank() over (order by no_rentals desc) "rank" 
from abc 
inner join orders on orders.CID = abc.CID;

我使用了这个查询,但它并不普遍。如何在number_of_rentals上使用sum函数和此查询?

1 个答案:

答案 0 :(得分:0)

Select Top 10 
         orders.cid
       , abc.name
       , SUM(orders.no_rentals) TotalRentals
       , rank() over (order by SUM(orders.no_rentals) desc) [rank] 
from abc 
inner join orders on orders.CID = abc.CID
Group By orders.cid, abc.name
Order By TotalRentals DESC