组合两个表
SELECT FirstName, LastName, City, StateFROM Person a LEFT JOIN Address b ON a.PersonId = b.PersonId;
第二高的薪水
SELECT CASE WHEN FirstHighestSalary = SecondHighestSalary THEN NULL ELSE SecondHighestSalary END AS SecondHighestSalaryFROM (SELECT MIN(Salary) AS SecondHighestSalary, MAX(Salary) AS FirstHighestSalary FROM (SELECT * FROM Employee ORDER BY Salary DESC LIMIT 2) a) a;
第N高的薪水
SELECT CASE WHEN rank_min < N THEN NULL ELSE a.Salary END AS salaryFROM (SELECT Salary, MIN(rank) AS rank_min FROM (SELECT a.Salary, rank FROM (SELECT Salary FROM (SELECT Salary, @row_num:=@row_num + 1 AS rank FROM (SELECT *, @row_num:=0 FROM Employee ORDER BY Salary DESC) a) a WHERE rank = N) a INNER JOIN (SELECT Salary, @row_num:=@row_num + 1 AS rank FROM (SELECT *, @row_num:=0 FROM Employee ORDER BY Salary DESC) a) b ON a.Salary = b.Salary) a) a;
分数排名
SELECT a.Score, rankFROM (SELECT Score, num, @row_num:=@row_num + 1 AS rank FROM (SELECT Score, COUNT(1) AS num, @row_num:=0 FROM Scores GROUP BY Score ORDER BY Score DESC) a) a INNER JOIN Scores b ON a.Score = b.ScoreORDER BY a.Score DESC;
连续出现的数字
SELECT DISTINCT c.Num AS ConsecutiveNumsFROM (SELECT Num, @row_num:=@row_num + 1 AS rank FROM (SELECT *, @row_num:=0 FROM Logs) a) a LEFT JOIN (SELECT Num, @row_num:=@row_num + 1 AS rank FROM (SELECT *, @row_num:=0 FROM Logs) a) b ON a.rank = b.rank + 1 LEFT JOIN (SELECT Num, @row_num:=@row_num + 1 AS rank FROM (SELECT *, @row_num:=0 FROM Logs) a) c ON a.rank = c.rank + 2WHERE a.Num = b.Num AND a.Num = c.Num;
超过经理收入的员工
SELECT a.Name AS EmployeeFROM (SELECT Name, Salary, ManagerId FROM Employee WHERE ManagerId IS NOT NULL) a LEFT JOIN (SELECT Id, Salary FROM Employee) b ON a.ManagerId = b.idWHERE a.Salary > b.Salary
查找重复的电子邮箱
SELECT EmailFROM (SELECT Email, COUNT(1) AS num FROM Person GROUP BY Email) aWHERE a.num > 1
从不订购的客户
SELECT a.Name AS CustomersFROM Customers a LEFT JOIN Orders b ON a.Id = b.CustomerIdWHERE b.CustomerId IS NULL
部门工资最高的员工
SELECT c.Name AS Department, b.Name AS Employee, SalaryFROM (SELECT DepartmentId, MAX(Salary) AS max_salary FROM (SELECT DepartmentId, salary FROM Employee) a GROUP BY DepartmentId) a INNER JOIN (SELECT Name, Salary, DepartmentId FROM Employee) b ON a.DepartmentId = b.DepartmentId AND a.max_salary = b.Salary INNER JOIN Department c ON a.DepartmentId = c.Id
换座位
SELECT id - 1 AS id, studentFROM seatWHERE id MOD 2 = 0UNION SELECT CASE WHEN id + 1 <= id_max THEN id + 1 ELSE id END AS id, studentFROM ( SELECT * FROM seat LEFT JOIN (SELECT max(id) AS id_max FROM seat) c ON seat.id <= c.id_max ) aWHERE id MOD 2 = 1ORDER BY id
作者:真依然很拉风
链接:https://www.jianshu.com/p/4dc00631a877
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦