快乐SQL做题 - Day5

Hello!!结束快乐的旅行~今天是SQL DAY 5啦~

一起来看看今天有什么题目吧~

闯关开始!

关卡1-  员工薪水中位数

思路:

在做这道题之前,我们需要了解窗口函数

因为我们要创建两个新的column:一个在每个company中排序,产生row number; 另一个column是count这个company有多少员工

最后计算row_number = 中位数

SELECT Id, Company, Salary

FROM

(SELECT Id, Company, Salary,

    ROW_NUMBER() OVER (PARTITION BY company ORDER BY Salary ASC, id ASC) AS row_num,

    COUNT(Id) OVER (PARTITION BY company) AS count_id

    FROM Employee ) AS ans

WHERE row_num IN (FLOOR((count_id + 1)/2), FLOOR((count_id + 2)/2))

最后一行这么写的原因是,如果count id 为奇数,比如3,那么floor(4/2) = 2, floor(5/2)=2,当他为偶数,那就返回两个值。符合了我们题目的要求。

恭喜过关!进入下一关!


关卡2 -  至少有5名直接下属的经理


思路:

自连接之后就可以很好的完成啦~~

记得count可以在having里面使用~而having是在group by后面~~

select distinct b.name from employee a, employee b

where a.ManagerId = b.Id

group by b.Id

having count(b.Id) >= 5

恭喜过关!进入下一关!


关卡3 - 当选者

思路:

首先有两张表,我们一定是要先把两张表join在一起

加完我们先以姓名分组,再按照每个分组的计数给分组降序排序,使用 limit 1 取第一名即可。

select c.name from candidate c

join vote v

on c.id = v.CandidateId

group by c.name

order by count(v.CandidateId) desc

limit 1

恭喜过关!进入下一关!


关卡4 - 查询回答率最高的问题

思路:

我们先排除answer为null的情况

再按照问题分组

然后降序排序出 count(answer_id) ,看看回答的次数

最后limit1,就可以啦

答案:

select question_id as survey_log

from survey_log

where answer_id is not null

group by question_id

order by count(answer_id) desc

limit 1

恭喜过关!进入下一关!


关卡5 - 查询员工的累计薪水

思路:

还记得day4的关卡3吗~ 也是一道求累计和的题, 当时我说他的精髓在于让 a.month >= b.month 然后group by a.id 和 a.month, 这里也是一样,我们以后可以养成这样的思维,就是当要求cumulative的和,我们就这么做。当然,记得第一行是sum(b.salary)。

现在我们来解决另一个问题,题目还要求取掉最大月之后,求剩下每个月的近三个月工资 

所以我们用a.month-3 < b.month 限制只对最近三个月工资求和。

另外创建一个子查询, (a.id, a.month) not in (select id, max(month) from employee group by id)

通过限制not in max(month) ,我们排除了最大的月份。

答案:

select a.id, a.month, sum(b.salary) as Salary from employee a, employee b

where a.id = b.id

and a.month >= b.month

and a.month-3 < b.month 

and (a.id, a.month) not in (select id, max(month) from employee group by id)

group by a.id, a.month

order by id asc, month desc

恭喜过关!


今天学到的新知识:两个新的窗口函数, ROW_NUMBER() OVER (PARTITION BY ) 计算第几行, COUNT() OVER (PARTITION BY ) 计算出现的个数;求最大不一定要max(), order by 然后 limit 1 也是很好的选择。灵活运用,is null 和is not null;类似python中cunsum()求累计之和的套路。

明天继续闯关~yay ~

你可能感兴趣的:(快乐SQL做题 - Day5)