如果员工的开始日期和结束日期包含历史记录。我们怎么说有差距?
示例数据:
+------+-------------+-------------+
|EmpID | StartDate | EndDate |
+------+-------------+-------------+
| 555 | 7/8/2015 | 15/12/2015 |
| 555 | 16/12/2015 | 25/06/2016 |
| 555 | 28/06/2016 | 20/12/2016 | --Here 2 days gaps.
| 555 | 21/12/2016 | 31/12/9999 |
+------+-------------+-------------+
答案 0 :(得分:3)
假设没有重叠日期,您可以使用lag
获取之前的end_date并获取当前行的start_date的差异,并检查差异> 1(表示根据所示样本数据的间隙)。
select distinct emp_id
from (select t.*
,datediff(day,lag(end_date,1,end_date) over(partition by emp_id order by start_date),start_date) as diff
from tbl t
) t
where diff > 1
答案 1 :(得分:1)
如果是SQL Server> = 2012,则可以使用滞后
Select *, GapDays = Coalesce(DateDiff(Day,lag(EndDate) over(partition by empid order by Startdate), StartDate)-1, 0)
from #emp
输出如下:
+-------+------------+------------+---------+
| EmpId | StartDate | EndDate | GapDays |
+-------+------------+------------+---------+
| 555 | 2015-08-07 | 2015-12-15 | 0 |
| 555 | 2015-12-16 | 2016-06-25 | 0 |
| 555 | 2016-06-28 | 2016-12-20 | 2 |
| 555 | 2016-12-21 | 9999-12-31 | 0 |
+-------+------------+------------+---------+
答案 2 :(得分:1)
这是我的方法:
create table #emp(EmpID int,StartDate date,EndDate date)
insert into #emp values
(555,'7/8/2015', '15/12/2015'),
(555,'16/12/2015','25/06/2016'),
(555,'28/06/2016','20/12/2016'), --Here 2 days gaps.
(555,'21/12/2016','31/12/9999')
查询:
select iq.EmpID,iq.StartDate,iq.EndDate, (DATEDIFF(day,iq.prev_date,iq.startdate)-1) as 'gap'
from
(select *, lag(enddate) over (partition by EmpID order by empid, startdate) as prev_date
from #emp
)iq
where (DATEDIFF(day,iq.prev_date,iq.startdate)-1) > 0
输出:
EmpID StartDate EndDate gap
----------- ---------- ---------- -----
555 2016-06-28 2016-12-20 2