欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

以部门号分组,查询薪水前三的员工

程序员文章站 2022-07-07 09:47:04
...
SELECT
    * 
FROM
    emp AS a 
WHERE
    3 > ( SELECT count( * ) FROM emp WHERE deptno = a.deptno AND sal < a.sal ) 
ORDER BY
    a.deptno,
    a.sal
    
SELECT
    a.* 
FROM
    (
SELECT
    t1.*,
    ( SELECT count( * ) + 1 FROM emp WHERE deptno = t1.deptno AND sal < t1.sal ) AS group_id 
FROM
    emp t1 
    ) a 
WHERE
    a.group_id <= 3 
ORDER BY
    a.deptno,
    a.sal
    
SELECT
    t.* 
FROM
    ( SELECT ROW_NUMBER ( ) OVER ( PARTITION BY deptno ORDER BY sal DESC ) rn, b.* FROM emp b ) t 
WHERE
    t.rn <= 3;