1.各部门工资最高的员工(难度:中等)
注意:使用group by的时候,出现在select后面的字段,要么是是聚合函数中的,要么就是group by 中的字段
比如错误答案:
SELECT NAME , MAX(Salary) FROM Employee GROUP BY DepartmentId
这与题目中的数据不符,所以这么写是错误的
题解:
SELECT
Department.name AS 'Department',
Employee.name AS 'Employee',
Salary
FROM
Employee
JOIN
Department ON Employee.DepartmentId = Department.Id
WHERE
(Employee.DepartmentId , Salary) IN
( SELECT
DepartmentId, MAX(Salary)
FROM
Employee
GROUP BY DepartmentId
)
;
作者:LeetCode
链接:https://leetcode-cn.com/problems/department-highest-salary/solution/bu-men-gong-zi-zui-gao-de-yuan-gong-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
2.换座位(难度:中等)
这里面使用了交叉连结(CROSS JOIN)
使用逗号分隔两个表,并省略 ON 子句 (旧式写法)
SELECT
(CASE
WHEN MOD(id, 2) != 0 AND counts != id THEN id + 1
WHEN MOD(id, 2) != 0 AND counts = id THEN id
ELSE id - 1
END) AS id,
student
FROM
seat,
(SELECT
COUNT(*) AS counts
FROM
seat) AS seat_counts
ORDER BY id;
作者:LeetCode
链接:https://leetcode-cn.com/problems/exchange-seats/solution/huan-zuo-wei-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
3.分数排名(难度:中等)
对于 MySQL 解决方案,如果要转义用作列名的保留字,可以在关键字之前和之后使用撇号。例如 'Rank'
SELECT Score,
DENSE_RANK() OVER (ORDER BY score DESC) as 'Rank'
FROM Scores;