母公司拥有拥有雇员的公司。每个公司都可以雇用和任命一名雇员。
一个员工可以同时为多个公司工作。
在公司内部,聘用日期和任期不能重叠,但在公司之间可以重叠。雇用日期被认为是一个人的第一天就业,而任期日期被认为是一个人的最后就业日。
一个人可以有很多工作时期(离开和返回)。在职员工的任期为“ 9999-12-31”。
我如何获得不考虑重叠日期的母公司员工录用和任期的结果集?
源表:
+--------------+----------+-------------+-------------+
| employee_id | company | hire_date | term_date |
+--------------+----------+-------------+-------------+
| 1 | A | 2017-01-01 | 2017-07-01 |
| 1 | A | 2018-01-01 | 2018-06-15 |
| 1 | B | 2018-04-01 | 9999-12-31 |
+--------------+----------+-------------+-------------+
所需结果:
+--------------+-------------+-------------+
| employee_id | hire_date | term_date |
+--------------+-------------+-------------+
| 1 | 2017-01-01 | 2017-07-01 |
| 1 | 2018-01-01 | 9999-12-31 |
+--------------+-------------+-------------+
答案 0 :(得分:0)
从SQL Server 2012开始,您可以使用LAG
(更多信息here)在表的不同行之间比较值:
declare @tmp table (employee_id int, company varchar(10), hire_date date, term_date date)
insert into @tmp values
(1,'','2017-01-01','2017-07-01')
,(1,'','2018-01-01','2018-06-15')
,(1,'','2018-04-01','9999-12-31')
select employee_id, min(hire_date) as hire_date, max(term_date) as term_date
from
(
select employee_id, hire_date, term_date, max (tmp1) over (partition by employee_id order by hire_date asc) as tmp2
from
(
SELECT employee_id,
hire_date,
isnull (term_date, '9999-12-31') term_date,
case
when
(hire_date not between lag(hire_date) over (partition by employee_id order by hire_date asc)
and isnull( lag(term_date) over (partition by employee_id order by hire_date asc), '9999-12-31') )
or lag(hire_date) over (partition by employee_id order by hire_date asc) is null
then
row_number() over (partition by employee_id order by hire_date asc)
end as tmp1
FROM @tmp
) x
) y
group by employee_id, tmp2
结果: