LeetCode MySQL 615. 平均工资:部门与公司比较(over窗口函数)
发布日期:2021-07-01 03:30:44
浏览次数:3
分类:技术文章
本文共 1980 字,大约阅读时间需要 6 分钟。
文章目录
1. 题目
给如下两个表,写一个查询语句,求出在每一个工资发放日,每个部门的平均工资与公司的平均工资的比较结果 (高 / 低 / 相同)。
表: salary
| id | employee_id | amount | pay_date ||----|-------------|--------|------------|| 1 | 1 | 9000 | 2017-03-31 || 2 | 2 | 6000 | 2017-03-31 || 3 | 3 | 10000 | 2017-03-31 || 4 | 1 | 7000 | 2017-02-28 || 5 | 2 | 6000 | 2017-02-28 || 6 | 3 | 8000 | 2017-02-28 |
employee_id 字段是表 employee 中 employee_id 字段的外键。
| employee_id | department_id ||-------------|---------------|| 1 | 1 || 2 | 2 || 3 | 2 |
对于如上样例数据,结果为:
| pay_month | department_id | comparison ||-----------|---------------|-------------|| 2017-03 | 1 | higher || 2017-03 | 2 | lower || 2017-02 | 1 | same || 2017-02 | 2 | same |
解释
在三月,公司的平均工资是 (9000+6000+10000)/3 = 8333.33…
由于部门 ‘1’ 里只有一个 employee_id 为 ‘1’ 的员工,
所以部门 ‘1’ 的平均工资就是此人的工资 9000 。 因为 9000 > 8333.33 ,所以比较结果是 ‘higher’。第二个部门的平均工资为 employee_id 为 ‘2’ 和 ‘3’ 两个人的平均工资,为 (6000+10000)/2=8000 。
因为 8000 < 8333.33 ,所以比较结果是 ‘lower’ 。在二月用同样的公式求平均工资并比较,比较结果为 ‘same’ ,
因为部门 ‘1’ 和部门 ‘2’ 的平均工资与公司的平均工资相同,都是 7000 。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/average-salary-departments-vs-company 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
# Write your MySQL query statement belowselect distinct pay_month, department_id, case when dep_avg > total_avg then 'higher' when dep_avg = total_avg then 'same' else 'lower' end as comparisonfrom( # 平均部门工资, 公司平均工资 select department_id, avg(amount) over(partition by department_id, date_format(pay_date, "%Y-%m")) dep_avg, date_format(pay_date, "%Y-%m") pay_month, avg(amount) over(partition by date_format(pay_date, "%Y-%m")) total_avg from salary s left join employee using(employee_id)) t
我的CSDN
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
转载地址:https://michael.blog.csdn.net/article/details/107730203 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
网站不错 人气很旺了 加油
[***.192.178.218]2024年04月13日 12时51分43秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
x265-1.7版本-encoder/dpb.h注释
2019-05-02
x265-1.7版本-encoder/encoder.cpp注释
2019-05-02
x265-1.7版本-encoder/encoder.h注释
2019-05-02
x265-1.7版本-encoder/frameencoder.cpp注释
2019-05-02
x265-1.7版本-encoder/frameencoder.h注释
2019-05-02
x265-1.7版本-encoder/motion.cpp注释
2019-05-02
高阶函数
2019-05-02
继承和多态
2019-05-02
获取对象信息
2019-05-02
实例属性和类属性
2019-05-02
使用__slots__
2019-05-02
使用@property
2019-05-02
多重继承
2019-05-02
定制类
2019-05-02
使用枚举类
2019-05-02
使用元类
2019-05-02
错误、调试和测试
2019-05-02
StringIO和BytesIO
2019-05-02
SMTP发送邮件
2019-05-02
POP3收取邮件
2019-05-02