oracle中排名前10行

时间:2016-02-28 22:48:43

标签: sql oracle

我有两张桌子。 abc(CID(pk),cname,) order(order_id(pk),CID(fk),number_of_rentals)

我想根据租金数量获取前10名客户。

SELECT  cid, sum(no_rentals) as sum 
FROM orders 
group by cid, no_rentals
order by no_rentals desc;

如何在上面的查询中使用rownum函数来获取所需的输出

1 个答案:

答案 0 :(得分:4)

将您的查询包装在:

SELECT * FROM ( your_query ) WHERE ROWNUM <= 10;

但是,您的查询看起来不会像您想要的那样,因为GROUP BY no_renalts意味着每个不同的no_rentals值将在其自己的组中,并且您不会对这些值求和对于每个客户,您可能不希望将其包含在GROUP BY中。此外,如果您想按租赁总数订购,那么您希望ORDER BY SUM( no_rentals )(或其别名)如下:

SELECT   cid,
         SUM(no_rentals) as total_no_rentals 
FROM     orders 
GROUP BY cid
ORDER BY total_no_rentals DESC;

然后你可以像这样应用行限制:

SELECT *
FROM   (
  SELECT   cid,
           SUM(no_rentals) as total_no_rentals
  FROM     orders 
  GROUP BY cid
  ORDER BY total_no_rentals DESC
)
WHERE ROWNUM <= 10;