leetcode--mysql题目总结(二)

目录

题目一:上升的温度

题目二:大的国家

题目三:超过五名学生的课

*题目四:部门工资前三高的员工


题目一:上升的温度

题目链接:https://leetcode-cn.com/problems/rising-temperature/

思路:在mysql中,日期类型的数据进行比较,不能直接使用减法,

        需要使用datediff()函数进行比较

select w1.id from Weather w1
join Weather w2
on datediff(w1.recorddate,w2.recorddate)=1
and w1.Temperature > w2.Temperature

题目二:大的国家

题目链接:https://leetcode-cn.com/problems/big-countries/

思路:使用where语句进行条件过滤,两个语句之间是或者的关系,故使用or.

select name , population , area
from World
where population > 25000000
or area > 3000000;

题目三:超过五名学生的课

题目链接:https://leetcode-cn.com/problems/classes-more-than-5-students/

 思路:按照class分区,按照student进行数量统计,注意对student统计前,

            先使用distinct student对student进行去重。

select class
from courses
group by class
having count(distinct student) >=5

*题目四:部门工资前三高的员工

首先:解释为什么不能使用group by进行部门分组,然后求出对应部门工资前三高的员工?

          group by是分组函数不假,但是分组后有两种用法

         1)若直接分完组直接select * ,其实这个分组后的查询返回的不是各个组的所有数据,

               而是返回分完组后各个组的第一条数据

         2)分组后与聚合函数一起使用,max()/min()因此如果要查询分组后每个组的

              第一名或者最后一名 ,我们可以使用group by(),但是求前三名group by 就无能为力了。

方法一:使用mysql求解:

     1

     1)首先找出公司里面前3高的薪水

       翻译过来就是查找e1表工资大小即e1.Salary,其要满足的条件是e2表中,

       相同部门id的人,他的工资比e1表中工资高的数量(去重之后)要小于3。

select e1.Salary
from Employee e1
where 
(
    select count(distinct e2.Salary)
    from Employee e2
    where e1.Salary < e2.Salary and 
          e1.departmentId = e2.departmentId
) <3

2)再把员工表和部门表做连接

    借鉴上面的思路:两表连接,加一个where进行条件判断,判断条件

就是count <3

select d.Name as 'Department', e1.Name as 'Employee', e1.Salary
from employee e1 
join Department d
on e1.DepartmentId = d.Id
where 
(
    select count(distinct e2.Salary)
    from Employee e2
    where e1.Salary < e2.Salary and 
          e1.departmentId = e2.departmentId
) <3

方法二:使用窗口函数

思路:先建一张临时表:临时表有所需要查询的列和薪水排名,薪水排名用窗口函数

          dense_rank() over(按某字段分区按某字段排序)

eg: dense_rank() over(partition by e.departmentId order by e.Salary ) as a (其一个别名a)

     然后从这张临时表张查询我们需要的列,查询条件就是判断排名这一列是否符合条件。

select temp.Department, temp.Employee, temp.Salary
from 
(
select d.Name as 'Department', e.Name as 'Employee', e.Salary as 'Salary',
dense_rank() over(partition by e.departmentId order by e.Salary desc ) a
from employee e
join department d
on e.departmentid = d.id
) temp
where temp.a <4;

总结:牢记窗口函数的意思,用法。       

猜你喜欢

转载自blog.csdn.net/yezonghui/article/details/115283626