以部门号分组,查询薪水前三的员工
程序员文章站
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;
上一篇: 数据库范式与实例
推荐阅读