简体   繁体   English

SQL - 获取行的最小值并检查此最小值是否在行中至少 2 次

[英]SQL - get MIN value of row and check this MIN value to be in row at least 2 times

What I'm trying to achieve is this:我想要实现的是:
1) Get the minimum value of a salary in the table for every department. 1) 获取表中每个部门的工资最小值。
2) If this minimum value exists in the table at least two times for every department, then show its department id. 2) 如果这个最小值在每个部门的表中至少存在两次,则显示其部门 id。

Example:例子:

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

Result:结果:

department_id
1
2

If I followed you correctly, you want departments where more than one employee has the lowest salary.如果我没听错的话,你需要一个以上员工工资最低的部门。

Here is an approach using window functions, which works by comparing row_number() and rank() :这是一种使用 window 函数的方法,它通过比较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

If I understand correctly, you want the departments where the minimum salary occurs at least twice.如果我理解正确,您希望最低工资至少出现两次的部门。 This makes me think window functions:这让我觉得 window 功能:

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;

Note that you don't need a select distinct , because this chooses at most one row per department.请注意,您不需要select distinct ,因为每个部门最多选择一行。

    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM