给定如下数据:
id | name | salary |
1 | Alice | 2000 |
2 | Bob | 3000 |
3 | Charlie | 2000 |
4 | David | 2000 |
5 | Eddie | 1500 |
SELECT * FROM employees
ORDER BY salary DESC
FETCH FIRST 2 ROWS ONLY;
返回前两行数据,如下:
id | name | salary |
2 | Bob | 3000 |
1 | Alice | 2000 |
如果希望salary=2000的记录全部返回,可以使用TIES子句,
SELECT * FROM employees ORDER BY salary DESC FETCH FIRST 2 ROWS WITH TIES;
其结果如下:
id | name | salary |
2 | Bob | 3000 |
1 | Alice | 2000 |
3 | Charlie | 2000 |
4 | David | 2000 |
否则就要使用DENSE_RANK分析函数,如下:
SELECT c, DENSE_RANK() OVER ( ORDER BY c ) dense_rank_number FROM dense_ranks