它们的语法是一样的,如下:
ROW_NUMBER() OVER([PARTITION BY col1] ORDER BY col2)
DENSE_RANK() OVER([PARTITION BY col1] ORDER BY col2)
RANK() OVER([PARTITION BY col1] ORDER BY col2)
其中[PARTITION BY col1]是可选的,即不分组,或者说所有满足条件的数据一组。
WITH workers AS(
SELECT 'DOM1' dept, 'zhangsan' names , 23 age, 4000 salaries FROM dual UNION ALL
SELECT 'DOM1' dept, 'lisi' names , 35 age, 9000 salaries FROM dual UNION ALL
SELECT 'DOM1' dept, 'zhangchen' names, 35 age, 9000 salaries FROM dual UNION ALL
SELECT 'DOM1' dept, 'qiansi' names , 35 age, 4000 salaries FROM dual UNION ALL
SELECT 'DOM2' dept, 'wangwu' names , 26 age, 6500 salaries FROM dual UNION ALL
SELECT 'DOM2' dept, 'maliu' names , 28 age, 6000 salaries FROM dual UNION ALL
SELECT 'DOM2' dept, 'zhaoqi' names , 26 age, 5000 salaries FROM dual UNION ALL
SELECT 'DOM1' dept, 'liba' names , 23 age, 3000 salaries FROM dual
)
SELECT s.names,s.salaries,s.names,dept, ROW_NUMBER() OVER(PARTITION BY dept ORDER BY salaries DESC)rank FROM workers s;
结果如下,RANK列没有重复。
SELECT s.names, dept, s.salaries, DENSE_RANK() OVER(PARTITION BY dept ORDER BY salaries DESC)rank FROM workers s;
结果如下,相同salaries时,RANK有重复,但连续。
SELECT s.names, dept, s.salaries, RANK() OVER(PARTITION BY dept ORDER BY salaries DESC)rank FROM workers s;
结果如下,相同salaries时,RANK有重复,同时不连续。