[英]SQL - get MIN value of row and check this MIN value to be in row at least 2 times
我想要實現的是:
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
如果我沒聽錯的話,你需要一個以上員工工資最低的部門。
這是一種使用 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
如果我理解正確,您希望最低工資至少出現兩次的部門。 這讓我覺得 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;
請注意,您不需要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.