【问题标题】:Find mix and max in sql from each partition从每个分区的 sql 中查找 mix 和 max
【发布时间】:2021-08-28 21:08:53
【问题描述】:

我正在尝试查找员工的最低和最高工资以及以下案例中的 dept_id -

Emp表:

emp_id dept_id salary
----------------------
1         1     100
1         2     200
1         3     300

期望的输出:

emp_id dept_id salary
---------------------
1         1     100
1         3     300

这是我想出来的,但不确定这是否正确-

select emp_id, dept_id, salary
from emp x
where salary in (select min(sal) 
                 from emp y 
                 where y.emp_id = x.emp_id)
   or salary in (select max(sal) 
                 from emp y 
                 where y.emp_id = x.emp_id)

【问题讨论】:

    标签: sql oracle max min


    【解决方案1】:

    如果您希望 具有最低和最高工资,那么一种方法使用窗口函数:

    select emp_id, dept_id, salary
    from (select e.*,
                 row_number() over (partition by emp_id order by salary asc) as seqnm_asc,
                 row_number() over (partition by emp_id order by salary desc) as seqnm_desc
          from emp e
         ) e
    where 1 in (seqnum_asc, seqnum_desc);
    

    【讨论】:

      【解决方案2】:

      我认为你可以这样做:

      select emp_id, dept_id, min(salary) as min_salary, max(salary) as max_salary
      from Employees
      group by emp_id
      

      此查询应该使用the "group by" clause(这是Oracle 文档,基于您的标签)以更简洁的格式执行您所请求的操作。

      考虑了解有关分组集的更多信息。

      【讨论】:

      • 恕我直言 group by 也必须有 2 列;对吗?
      • 此查询将失败,因为在 dept_id 上没有使用聚合函数。此外,这里的要求是获取 emp_id 1 的 2 条记录,一条具有最低薪水,另一条具有最高薪水,并具有相应的 dept_id。查看所需的输出。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 2014-11-21
      • 1970-01-01
      相关资源
      最近更新 更多