SQL 查詢:對于每個部門,找到該部門教師的最高工資。
Instructor schema:Instructor( ID , name, dept_name,salary) Id 主鍵,dept_name 外鍵參考部門。
部門(部門名稱,建筑,預算)
教師表值:
ID Iname dept_name salary
10101 Srinivasan Comp. Sci. 65000
12121 Wu Finance 90000
15151 Mozart Music 40000
22222 Einstein Physics 95000
32343 El Said History 60000
33456 Gold Physics 87000
45565 Katz Comp. Sci. 75000
58583 Califieri History 62000
76543 Singh Finance 80000
76766 Crick Biology 72000
83821 Brandt Comp. Sci. 92000
98345 Kim Elec. Eng. 80000
如果我們嘗試手動找出最高工資,
Brandt Comp. Sci
Wu Finance
Mozart Music
Einstein Physics
Califieri History
Crick Biology
Kim Elec. Eng.
現在我運行這個查詢,
select distinct
T.Iname,
T.dept_name
from instructor as T,
instructor as S
where T.salary > S.salary
group by T.dept_name;
我有
Kim Elec. Eng.
Brandt Comp. Sci.
Crick Biology
Singh Finance
Gold Physics
Califieri History
我的金融和物理結果不正確,甚至不包括音樂。
我找不到我的錯誤。我想知道哪里需要修改?
謝謝你。
uj5u.com熱心網友回復:
在 MySQL 8 上,這個問題很容易使用RANK:
WITH cte AS (
SELECT *, RANK() OVER (PARTITION BY dept_name ORDER BY salary DESC) rnk
FROM department
)
SELECT Iname, dept_name, salary
FROM cte
WHERE rnk = 1;
請注意,如果出現平局,上述內容將報告給定部門內共享最高薪水的兩名或更多教師。
uj5u.com熱心網友回復:
使用 EXISTS
select T.Iname,
T.dept_name
from instructor as T
where not exists (select 1
from instructor as S
where S.dept_name = T.dept_name
and T.salary < S.salary);
uj5u.com熱心網友回復:
另一種方法是在子查詢 td_1 中找到部門的最大工資,然后使用工資和部門將其與資料表連接
select td.Iname, td.dept_name, td.salary
from test_data td
join (select max(salary) salary, dept_name
from test_data td
where td.dept_name = dept_name
group by dept_name) td_1
on td_1.dept_name = td.dept_name
and td_1.salary = td.salary
uj5u.com熱心網友回復:
我認為下面的 SQL 會起作用。
select Iname, dept_name from instructor as t1 where t1.salary=(select max(salary) from instructor as t2 where t1.dept_name = t2.dept_name);
或者
select t1.Iname, t1.dept_name from instructor as t1 left join instructor as t2 on t1.dept_name = t2.dept_name and t1.salary < t2.salary where t2.dept_name is NULL;
uj5u.com熱心網友回復:
嘗試這個:
SELECT ID, Iname, dept_name, salary
FROM instructors
GROUP BY Iname,dept_name
ORDER BY salary DESC ;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/353897.html
