您的位置:首页 > 数据库 > Oracle

用rank对oracle分组排序

2005-11-16 10:46 495 查看
前些日子做了个数据分组后重新排序的报表。是用crystal脚本写的,先设置一个全局变量,让其自加,然后在每一个group head里面清零。代码很简单,我就不贴了。
过段日子,有同事求一个分组后重新排序的语句,他以为我的报表是用类似的sql做的。其实如果用oracle的话,rank函数也可以实现分组后重新排序。
RANK Function
The RANK function produces an ordered ranking of rows starting with a rank of one. Users specify an optional
PARTITION clause and a required ORDER BY clause. The PARTITION keyword is used to define where the rank
resets. The specific column which is ranked is determined by the ORDER BY clause. If no partition is specified,
ranking is performed over the entire result set. RANK will assign a rank of 1 to the smallest value unless descending
order is used. The following example ranks salesmen for each region based on their sales amount.
SELECT sales_person, sales_region, sales_amount,
RANK() OVER (PARTITION BY s_region ORDER BY s_amount DESC)
FROM Sales_table;
sales_person ,sales_region ,sales_amount, rank
Adams East 100 1
Baker East 99 2
Connors East 89 3
Davis East 75 4
Edwards West 74 1
Fitzhugh West 66 2
Gariabaldi West 45 3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: