Join

如何將此相關查詢重寫為 JOIN?

  • April 13, 2020

我剛剛進入 SQL 並遇到一些困難圍繞相關查詢包裹我的頭。我仍在努力掌握它,但想知道將這個語句重寫為 JOIN 的正確語法是什麼。基本上我有一個部門的員工名單,想知道每個部門的最高薪水。這是作為相關查詢的查詢:

SELECT dept, name, salary 
FROM employees AS a 
WHERE salary >= ALL 
(
 SELECT salary 
 FROM employees b 
 WHERE a.dept = b.dept AND salary > 0
)

一種變體:

SELECT
 a.dept,
 a.name,
 b.salary
FROM employees AS a 
JOIN (
 SELECT
   MAX(c.salary) salary,
   c.dept
 FROM employees AS c
GROUP BY c.dept
) b
 ON a.dept = b.dept

如果您正在使用TSQL,您可以在內部替換JOINCROSS APPLYon moveON子句並將其替換為WHERE

引用自:https://dba.stackexchange.com/questions/264923