思路:先将两表连结,再在分组中取最大值后连结
select e.employee,e.salary,d.department_name department from Employee as e join Department as d on e.departmentid=d.department_id;
之后就不会了,连结给我整懵了。。。
正确答案:
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 ) ;
有句话特别重要:有可能有多个员工同时拥有最高工资,所以最好在这个查询中不包含雇员名字的信息。
思路:偶数上移一位,奇数下移一位,如果最后一位是奇数,则不变。
我想用if实现,感觉if比case...when...then写起来更简便。
我瞎写的 区分奇偶使用了%2,即取余;如果n%2=0,则说明n是偶数。
select if (id%2=0,id=replace(id,id,id-1),id=replace(id,id,id+1))as id,student from seat;
leecode评论区答案,膜!希望有朝一日我也这么牛X
select if (id%2=0, id-1, if(id=(select count(id) from seat),id,id+1)) as id , student from seat order by id asc;
我写的太麻烦了,用replace简直大材小用了,答主的if嵌套用的好熟练。。。
MYSQL中IF:
IF(X,A,B)
如果X为True,则返回A,否则,返回B
思路:dense_rank排序+窗口函数
select score as "Score",DENSE_RANK() over(order by score DESC) as "Rank" from Scores;
让我不太李姐的是leecode的重要提示:对于 MySQL 解决方案,如果要转义用作列名的保留字,可以在关键字之前和之后使用撇号。例如 `Rank`,或许李姐会理解?
select count(case when a.Num >= b.Num then count()+1 else count()=0 end) as ConsecutiveNums from Logs as a left join Logs as b on a.Num >= b.Num ;