CREATEFUNCTION getNthHighestSalary(N INT) RETURNSINT BEGIN SET N = N-1; RETURN ( SELECTDISTINCT Salary FROM Employee ORDERBY Salary DESC LIMIT N, 1 ); END
SELECTDISTINCT L1.Num AS ConsecutiveNums FROM Logs L1, Logs L2, Logs L3 WHERE L2.Id = L1.Id +1 AND L2.Num = L1.Num AND L3.Id = L1.Id +2 AND L3.Num = L1.Num;
仿照上题的写法,首先生成 res 临时表,统计数字和连续出现的次数,然后将连续出现次数大于等于 3 的数字去重输出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
SELECTDISTINCT Num AS ConsecutiveNums FROM ( SELECT Num, CASE -- 比较 WHEN@pre= Num THEN@cnt :=@cnt+1 -- 赋值 WHEN@pre := Num THEN@cnt :=1 END AS Cnt FROM Logs, ( SELECT@pre :=NULL, @cnt :=0) AS tmp )AS res WHERE res.Cnt >=3;
SELECT D.Name AS Department, E.Name AS Employee, Salary FROM Employee AS E, Department AS D, ( SELECT DepartmentId, MAX(Salary) AS Salary FROM Employee GROUPBY DepartmentId )AS tmp WHERE E.DepartmentId = D.Id AND D.Id = tmp.DepartmentId AND E.Salary = tmp.Salary;
官方题解是同样的思路,不过看起来可读性更强一些。
1 2 3 4 5 6 7 8 9 10
SELECT D.name AS Department, E.Name AS Employee, Salary FROM Employee AS E JOIN Department AS D ON E.DepartmentId = D.Id WHERE (E.DepartmentId, Salary) IN( SELECT DepartmentId, MAX(Salary) FROM Employee GROUPBY DepartmentId);
626. Exchange Seats
分类:数据库
难度:中等
题目表示 id 是连续自增的,因此不用考虑不连续的情况。
1 2 3 4 5 6 7
SELECT ( IF(s.id%2=0, s.id-1, IF(s.id=(SELECTMAX(id) FROM seat), s.id, s.id+1) ) ) AS id, student FROM seat s ORDERBY id;
学习一下官方题解使用 COALESCE() 函数,顺便根据题解里给出的函数说明链接可以推测 LeetCode 上使用的是 mysql 5.7 。
1 2 3 4 5
SELECT s1.id, COALESCE(s2.student, s1.student) AS student FROM seat s1 LEFTJOIN seat s2 ON ((s1.id +1) ^1) -1= s2.id ORDERBY s1.id;
185. Department Top Three Salaries
分类:数据库
难度:困难
根据 178 解题方法,先算出每个部门的工资排名,然后再把排名前三的员工信息输出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
SELECT D.Name AS Department, E.Name AS Employee, E.Salary FROM Department AS D,( SELECT DepartmentId, Name, Salary,( SELECTCOUNT(DISTINCT Salary) FROM Employee E2 WHERE E1.Salary <= E2.Salary AND E1.DepartmentId = E2.DepartmentId )AS'Rank' FROM Employee E1 )AS E WHERE D.Id = E.DepartmentId AND E.Rank <=3;
翻出官方题解,思路是判断比当前工资高的(去重)小于 3,相比之下执行速度较慢。
1 2 3 4 5 6 7 8 9 10 11
SELECT D.Name AS'Department', E1.Name AS'Employee', E1.Salary FROM Employee E1 JOIN Department D ON E1.DepartmentId = D.Id WHERE3> ( SELECTCOUNT(DISTINCT E2.Salary) FROM Employee E2 WHERE E2.Salary > E1.Salary AND E1.DepartmentId = E2.DepartmentId);
262. Trips and Users
分类:数据库
难度:困难
先根据 Id 进行两次表连接,一次连接用户,一次连接司机,同时满足 Banned 为 No;然后筛选日期并根据日期分组;最后根据分组情况计算输出,保留两位小数。
1 2 3 4 5 6 7 8 9 10 11 12
SELECT T.Request_at ASDay, ROUND(SUM(IF(T.Status LIKE'%cancel%', 1, 0))/COUNT(T.Status), 2) AS'Cancellation Rate' FROM Trips AS T JOIN Users AS U1 ON (T.Client_Id = U1.Users_Id AND U1.Banned ='No') JOIN Users AS U2 ON (T.Driver_Id = U2.Users_Id AND U2.Banned ='No') WHERE T.Request_at BETWEEN'2013-10-01'AND'2013-10-03' GROUPBY Request_at;
601. Human Traffic of Stadium
分类:数据库
难度:困难
题目的意思不是连续三天,特指三条连续记录,所以得用 id 条件才能过(摊手),根据 180 的解题思路拓展,考虑到所有情况即可。