【问题标题】:SQL - get MIN value of row and check this MIN value to be in row at least 2 timesSQL - 获取行的 MIN 值并检查此 MIN 值是否在行中至少 2 次
【发布时间】:2020-07-28 21:01:54
【问题描述】:

我想要实现的是:
1) 获取表中每个部门工资的最小值。
2) 如果对于每个部门,该最小值在表中至少存在两次次,则显示其部门ID。

例子:

column1 name  salary department_id
id1     John1 10000  1
id2     John2 10000  1
id3     John3 30000  2
id4     John4 30000  2
id5     John5 50000  3
id6     John6 20000  4

结果:

department_id
1
2

【问题讨论】:

  • 同时指定预期结果。
  • 请向我们展示您对此样本数据的预期结果。

标签: sql oracle group-by aggregate-functions greatest-n-per-group


【解决方案1】:

如果我没听错的话,你会想要一个以上员工工资最低的部门。

这是一种使用窗口函数的方法,通过比较row_number()rank() 来工作:

select distinct department_id
from (
    select 
        t.*, 
        row_number() over(partition by department_id order by salary) rn,
        rank()       over(partition by department_id order by salary) rnk
    from mytable t
) t
where rnk = 1 and rn > 1

【讨论】:

    【解决方案2】:

    如果我理解正确,您希望最低工资至少出现两次的部门。这让我想到了窗口函数:

    select t.department_id
    from (select t.*,
                 count(*) over (partition by department_id, salary) as cnt,
                 row_number() over (partition by department_id order by salary) as seqnum
          from t
         ) t
    where seqnum = 1 and cnt > 1;
    

    请注意,您不需要select distinct,因为这会为每个部门选择最多一行。

    【讨论】:

      【解决方案3】:
          SELECT department_id
            FROM Employee
           WHERE Employee.salary = (select min(emp.salary) from Employee emp where emp.department_id = Employee.department_id) 
        GROUP BY department_id
          HAVING COUNT(1) >=2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-27
        • 1970-01-01
        • 2018-12-02
        • 1970-01-01
        • 2019-07-20
        • 2022-09-23
        • 2013-03-24
        • 1970-01-01
        相关资源
        最近更新 更多