带 group by 的 Oracle 分析函数

Oracle analytical function with group by

通常我们按 dept_name 分组并找到最高和最低工资。

select dept_name,sum(salary),max(salary).min(salary) from emp group by dept_name;

但是我如何找到获得最高薪水和最低薪水的员工的姓名。是否可以在单个 sql 语句中找到?

你可以在子查询的帮助下完成:

select emp_name from employee where salary = (select max(salary) from employee) 
or salary = (select min(salary) from employee) ;

你可以这样做

WITH cteDepts as (select dept_name,
                         sum(salary) AS TOTAL_SALARY,
                         max(salary) AS MIN_SALARY,
                         min(salary) AS MAX_SALARY
                    from emp
                    group by dept_name)
SELECT d.*, emin.EMP_NAME, emax.EMP_NAME
  FROM cteDepts d
  INNER JOIN EMP emin
    ON emin.SALARY = d.MIN_SALARY
  INNER JOIN EMP emax
    ON emax.SALARY = d.MAX_SALARY

我不知道您的 EMP table 中的员工姓名列是什么,所以我使用了 EMP_NAME。如果列名与此不同,您需要更改查询以使用正确的列名。

祝你好运。

您可以使用FIRST函数:

SELECT dept_name, SUM(salary), MAX(salary), MIN(salary),
    MAX(emp_name) KEEP (DENSE_RANK FIRST ORDER BY salary) AS Min_salary_emp,
    MAX(emp_name) KEEP (DENSE_RANK LAST ORDER BY salary) as  Max_salary_emp 
FROM emp 
GROUP BY dept_name;

请注意,如果您有多名员工的薪水相同,您只会获得其中一名员工。

根据您的要求,您还可以使用 Pattern Matching

SELECT dept_name, MAX_salary, MIN_salary, salary, emp_name,
    Min_salary_emp, Max_salary_emp
FROM emp
MATCH_RECOGNIZE (
    PARTITION BY dept_name
    ORDER BY salary
    MEASURES 
        FINAL MIN(salary) AS MIN_salary,
        FINAL MAX(salary) AS MAX_salary,
        a.emp_name AS Min_salary_emp,
        c.emp_name AS Max_salary_emp
    ALL ROWS PER MATCH
    PATTERN ( (a+ {- b* -} c+) | a )
    DEFINE
    a AS salary = MIN(salary),
    c AS salary = MAX(salary)
);