Sql分组统计top-n或bottom-n

各个部门工资最高的前N个员工

Oracle写法

SELECT department_id, first_name, last_name, salary
FROM
(
  SELECT
    department_id, first_name, last_name, salary,
    ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary desc) rn
  FROM HR.employees
)
WHERE rn <= 3
ORDER BY department_id, salary DESC, last_name;

Mysql写法

SELECT
    t.department_id,
    GROUP_CONCAT(t.first_name ORDER BY t.salary DESC)
FROM 
(
SELECT 1 AS department_id, 'tom' AS first_name, 'smith' AS last_name, 12 AS salary UNION ALL
SELECT 1 AS department_id, 'jes' AS first_name, 'team' AS last_name, 11 AS salary UNION ALL
SELECT 2 AS department_id, 'xxx' AS first_name, 'aaa' AS last_name, 10 AS salary UNION ALL
SELECT 2 AS department_id, 'ttt' AS first_name, 'bbb' AS last_name, 13 AS salary 
) t
GROUP BY department_id;

你可能感兴趣的:(SQL)