LeetCode MySQL 615. 平均工资:部门与公司比较(over窗口函数)
发布日期:2021-07-01 03:30:44
浏览次数:4
分类:技术文章
本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年04月11日 04时23分47秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
[9] JMeter-常用函数的使用
2021-07-04
[12] JMeter-结果分析之图形图表
2021-07-04
使用aspose.words 18.6实现pdf文档转换
2021-07-04
Java数组详解
2021-07-04
vs中动态DLL与静态LIB工程中加入版本信息的方法
2021-07-04
大数据分析技术与应用一站式学习(值得收藏)_v20200418
2021-07-04
Qt 在windows下的串口读写
2021-07-04
自定义Starter
2021-07-04
分布式事务原理探究(一)
2021-07-04
spring cloud consul 应用的多实例名的解决
2021-07-04
人工智能为什么这么火?看看安防江湖30年血战就知道了
2021-07-04
“前端智能为安防产生新的数据价值”
2021-07-04
(8)CMake入门笔记--CMake语法
2021-07-04
头文件中 #ifndef---#define---#endif的作用
2021-07-04
Ant内置任务之whichresource
2021-07-04
Ant内置任务之symlink
2021-07-04
深入理解python--线程、进程与协程(1)
2021-07-04
字符串的排序
2021-07-04
内存分配(mallloc,calloc,realloc,new)
2021-07-04