SQL - 选择分组列上的最小值和最大值
我想使用 SQL 查询选择每个部门的员工开始和结束日期。考虑到员工可能会回到以前的部门。
当对(不相关的)列(例如新地址、职务)进行更改时,系统会创建新的 FromDate 和 ToDate,每个员工都有几行。
我所拥有的:
EmpID | DeptCode | FromDate | ToDate |
---|---|---|---|
201 | 40 | 2016-08-01 00:00:00.000 | 2017-08-31 00:00:00.000 |
201 | 40 | 2017-08-01 00:00:00.000 | 2018-09-30 00:00:00.000 |
201 | 80 | 2018-10-01 00:00:00.000 | 2019-05-31 00:00:00.000 |
201 | 80 | 2019-06-01 00:00:00.000 | 2020-06-30 00:00:00.000 |
201 | 80 | 2020-07-01 00:00:00.000 | 2022-02-28 00:00:00.000 |
201 | 40 | 2022-03-01 00:00:00.000 | 9999-12-31 00:00:00.000 |
302 | 10 | 2022-01-01 00:00:00.000 | 9999-12-31 00:00:00.000 |
我想要实现的是
EmpID | DeptCode | FromDate | ToDate |
---|---|---|---|
201 | 40 | 2016-08-01 00:00:00.000 | 2018-09-30 00:00:00.000 |
201 | 80 | 2018-10-01 00:00:00.000 | 2022-02-28 00:00:00.000 |
201 | 40 | 2022-03-01 00:00:00.000 | 9999-12-31 00:00:00.000 |
302 | 10 | 2022-01-01 00:00:00.000 | 9999-12-31 00:00:00.000 |
I want to select the employees' start and end dates for each department using a SQL query. Taking into mind that an employee might return to a previous department.
As the system creates a new FromDate and ToDate when changes are created to (irrelevant) columns such as a new address, title each employee has several rows.
What I have:
EmpID | DeptCode | FromDate | ToDate |
---|---|---|---|
201 | 40 | 2016-08-01 00:00:00.000 | 2017-08-31 00:00:00.000 |
201 | 40 | 2017-08-01 00:00:00.000 | 2018-09-30 00:00:00.000 |
201 | 80 | 2018-10-01 00:00:00.000 | 2019-05-31 00:00:00.000 |
201 | 80 | 2019-06-01 00:00:00.000 | 2020-06-30 00:00:00.000 |
201 | 80 | 2020-07-01 00:00:00.000 | 2022-02-28 00:00:00.000 |
201 | 40 | 2022-03-01 00:00:00.000 | 9999-12-31 00:00:00.000 |
302 | 10 | 2022-01-01 00:00:00.000 | 9999-12-31 00:00:00.000 |
What I want to achieve is
EmpID | DeptCode | FromDate | ToDate |
---|---|---|---|
201 | 40 | 2016-08-01 00:00:00.000 | 2018-09-30 00:00:00.000 |
201 | 80 | 2018-10-01 00:00:00.000 | 2022-02-28 00:00:00.000 |
201 | 40 | 2022-03-01 00:00:00.000 | 9999-12-31 00:00:00.000 |
302 | 10 | 2022-01-01 00:00:00.000 | 9999-12-31 00:00:00.000 |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为此,我们需要创建一些可以为我们的组使用的东西(答案末尾的 DBFiddle)
看看这个示例,
结果是
现在让我们看看最后两列,
假设您将它们彼此相减,您将得到
现在这个“计算的分组依据值”,我们可以用于我们的实际分组依据,
这将为您提供这个
您可以在此找到完整的代码和结果 DBFiddle
To do this, we need to create something that we can user for our group by (DBFiddle at the end of the answer)
Look at this sample
the result is
Now let's look at the last 2 columns,
suppose you would subtract them from each other, you would get
Now this "calculated group by value", we can use for our actual group by
Which will get you this
The full code and results you can find in this DBFiddle