【MySQL】排序取Top

2022-07-12  本文已影响0人  宅家学算法

leetcode 176

力扣 176

第二高理解为相同薪水同一等级,且连续排序

SELECT
    IFNULL(
      (SELECT DISTINCT Salary
       FROM Employee
       ORDER BY Salary DESC
        LIMIT 1 OFFSET 1),
    NULL) AS SecondHighestSalary

拓展->分组排序

ROW_NUMBER() OVER (
<PARTITION BY <expression>,[{,<expression>}...] >
 <ORDER BY <expression> [ASC|DESC],[{,<expression>}...]>) 

例:
SELECT 
 ROW_NUMBER() OVER (
 ORDER BY productName
 ) row_num,
    productName,
    msrp
FROM 
 products
ORDER BY 
 productName; 
RANK() OVER (
    PARTITION BY <expression>[{,<expression>...}]
    ORDER BY <expression> [ASC|DESC], [{,<expression>...}]
) 

例:
SELECT
    val,
    RANK() OVER (
        ORDER BY val
    ) my_rank
FROM
    rankDemo; 
排序结果
DENSE_RANK() OVER (
    PARTITION BY <expression>[{,<expression>...}]
    ORDER BY <expression> [ASC|DESC], [{,<expression>...}]
) 

例:
SELECT
    val,
    DENSE_RANK() OVER (
        ORDER BY val
    ) my_rank
FROM
    rankDemo; 
排序结果

对比

val ROW_NUMBER RANK() DENSE_RANK()
1 1 1 1
2 2 2 2
2 3 2 2
3 4 4 3
4 5 5 4
4 6 5 4
5 7 7 5
上一篇下一篇

猜你喜欢

热点阅读