mysql 中如何实现这样的查询

2017-06-21 21:56:10 +08:00
 lusheldon
mysql>desc salaries
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| emp_no | int(11) | NO | PRI | NULL | |
| salary | int(11) | NO | | NULL | |
| from_date | date | NO | PRI | NULL | |
| to_date | date | NO | | NULL | |
+-----------+---------+------+-----+---------+-------+

某员工的信息
+--------+--------+------------+------------+
| emp_no | salary | from_date | to_date |
+--------+--------+------------+------------+
| 111400 | 72446 | 1985-01-01 | 1986-01-01 |
| 111400 | 100416 | 1999-12-29 | 2000-12-28 |
| 111400 | 99971 | 2000-12-28 | 2001-12-28 |
| 111400 | 103244 | 2001-12-28 | 9999-01-01 |
+--------+--------+------------+------------+


查询所有曾经降过薪的员工 emp_no 以及降薪幅度
3299 次点击
所在节点    MySQL
10 条回复
hustlike
2017-06-21 21:59:16 +08:00
降过多次怎么算
lusheldon
2017-06-21 22:02:19 +08:00
@hustlike 降多次的情况下,应该也是可以查的吧。咱们先假设每个人最多可能降薪一次吧。
reus
2017-06-21 22:06:59 +08:00
select
distinct emp_no
from salaries a
join salaries b
on a.emp_no = b.emp_no and a.to_date > b.to_date and a.salary < b.salary
lusheldon
2017-06-21 22:09:57 +08:00
@reus 这个可能就是我要的答案,不熟悉数据库,没想过可以自己 join 自己。感谢!
reus
2017-06-21 22:14:43 +08:00
@lusheldon 但这个降薪幅度要计算的话,还得判断一下 a 和 b 的时间段是不是相邻的
lusheldon
2017-06-21 22:19:54 +08:00
@reus 加上条件 a.from_date=b.to_date 就能判断了吧。
reus
2017-06-21 22:23:31 +08:00
@lusheldon 如果没有断的话,是的
lusheldon
2017-06-21 22:27:04 +08:00
select a.emp_no,b.salary-a.salary, a.to_date
from salaries a join salaries b
on a.emp_no=b.emp_no and a.to_date>b.to_date and a.salary<b.salary and a.from_date=b.to_date;
奉上完整答案,再次感谢 @reus
wwww961h
2017-06-21 22:29:23 +08:00
用 join,把一个表当两个表用,特别简单
sohucw
2017-06-22 09:20:19 +08:00
select a.emp_no,b.salary-a.salary, a.to_date
from salaries a join salaries b
on a.emp_no=b.emp_no and a.to_date>b.to_date and a.salary<b.salary and a.from_date=b.to_date; 正解啊

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/370157

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX