SQL中的Min / Max Group问题

时间:2018-01-31 18:02:19

标签: sql sql-server

我正在尝试执行一个将整合员工合同列表的SQL查询。 它成功运作,除了某些员工多次来回换工作。

数据:

EmpNo   From Date   To Date Job Title
241780  2013-11-11  2013-11-24  Sales Associate
241780  2013-11-25  2014-01-04  Sales Associate
241780  2014-01-05  2014-02-28  Sales Associate - Accessories
241780  2014-03-01  2014-03-19  Sales Associate
241780  2014-03-20  2015-02-09  Sales Associate
241780  2015-02-10  2015-02-28  Sales Associate - Accessories
241780  2015-03-01  2016-10-16  Sales Associate - Accessories
241780  2016-10-17  2016-10-23  Customer Service Advisor
241780  2016-10-24  2016-11-13  Customer Service Advisor
241780  2016-11-14  2017-03-31  Customer Service Advisor
241780  2017-04-01  2030-01-01  Customer Service Advisor

问题来自我的代码:

Select [Employee No], 
MIN([Effective From Date]),
MAX([Effective To Date]),
[Job Title]
From [dbo].[MYTABLE]

Group by 
[Employee No],
[Job Title]
order by [Employee No],MIN([Effective From Date])

给我重叠日期

EmpNo   Start       TO          Job Title
241780  2013-11-11  2015-02-09  Sales Associate
241780  2014-01-05  2016-10-16  Sales Associate - Accessories
241780  2016-10-17  2030-01-01  Customer Service Advisor

我需要以下内容:

241780  2013-11-11  2014-01-04  Sales Associate
241780  2014-01-05  2012-02-28  Sales Associate - Accessories
241780  2014-03-01  2015-02-09  Sales Associate
241780  2015-02-10  2016-10-16  Sales Associate - Accessories
241780  2016-10-17  2030-01-01  Customer Service Advisor

我尝试过分区但没有成功,但不确定它会给我我之后的结果。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这是“差距和岛屿”问题的一个例子。一种方法使用行号的差异来定义组:

select empno, jobtitle, min(start) as start, max(to) as to
from (select t.*,
             row_number() over (partition by empno order by start) as seqnum_e,
             row_number() over (partition by empno, jobtitle order by start) as seqnum_ej,
      from t
     ) t
group by empno, jobtitle, (seqnum_e - seqnum_ej);