我有一个表和查询如下:
我正在尝试在[Assignment Start Date]
和[Assignment End Date]
之间为同一Employee Id
重叠记录。
简而言之,我需要那些Employee Id
的数据,这些数据是从下面的例子中分配给相同时间段或重叠时间段的。
e.g。
[Employee Id] [Assignment Start Date] [Assignment End Date] [Allocation Percentage]
100 2016-03-01 2017-02-28 100
102 2016-06-01 2016-12-31 100
102 2016-07-01 2016-10-30 100
102 2016-11-01 2017-01-31 100
103 2017-02-01 2017-05-30 100
102 2017-04-01 2017-06-30 100
102 2017-11-01 2017-01-31 100
104 2017-02-01 2017-05-01 100
CREATE TABLE #Result
(
PK INT IDENTITY(1,1),
[BU] VARCHAR(20),
[Division] VARCHAR(20),
[Product Name] VARCHAR(30),
[Employee ID] NVARCHAR(20),
[Resource Name] VARCHAR(50),
[Resource_ID] INT,
[Assignment Start Date] DATE,
[Assignment End Date] DATE,
[Allocation Percentage] INT,
[Location] VARCHAR(100),
[Development Manager] VARCHAR(50),
[Allocation] VARCHAR(20)
);
SELECT DISTINCT r1.PK, r1.Resource_ID,r1.[Employee ID], r1.[Assignment Start Date] AS 'Start 1' ,r1.[Assignment End Date] AS 'End 1' , r2.[Assignment Start Date] , r2.[Assignment End Date]
INTO #temp1
FROM #Result r1
INNER JOIN #Result r2
ON r1.[Employee ID] = r2.[Employee ID]
AND (r1.PK <> r2.PK)
AND ((r1.[Assignment Start Date] <= r2.[Assignment Start Date]) AND (r1.[Assignment End Date] >= r2.[Assignment Start Date]))
OR ((r1.[Assignment Start Date] > r2.[Assignment Start Date] AND r1.[Assignment Start Date] <= r2.[Assignment End Date]) AND (r1.[Assignment End Date] <= r2.[Assignment End Date]))
OR ((r1.[Assignment Start Date] > r2.[Assignment Start Date] AND r1.[Assignment Start Date] <= r2.[Assignment End Date]) AND (r1.[Assignment End Date] > r2.[Assignment End Date]))
OR (r1.[Assignment Start Date] = r2.[Assignment End Date])
我尝试使用上述查询,但它提供了与重叠员工相关的所有记录,即使该员工的条目不重叠。
在上面的示例中,有Employee Id
102
有2个重叠的条目,第3个条目没有重叠我想从此结果中删除它。请帮忙。
答案 0 :(得分:0)
CTE,row_number和自我加入
with CTE as
(
select PK, Resource_ID, [Employee ID] as Emp_ID, [Assignment Start Date] as s_Date, [Assignment End Date] as e_date,
row_number() over(partition by [Employee ID] order by [Assignment Start Date] ) as rn
from #Result
)
select t1.*, t2.*
from CTE t1
inner join CTE t2
on t1.Resource_ID = t2.Resource_ID
and t1.Emp_ID = t2.Emp_ID
and t2.rn = t1.rn +1
where t2.s_date <= t1.e_date
or t1.e_date is null -- allows for null end date
答案 1 :(得分:0)
您的SQL查询应如下所示:
SELECT DISTINCT r1.PK, r1.Resource_ID,r1.[Employee ID], r1.[Assignment Start Date] AS 'Start 1' ,r1.[Assignment End Date] AS 'End 1' , r2.[Assignment Start Date] , r2.[Assignment End Date]
INTO #temp1
FROM #Result r1
JOIN #Result r2 on r1.[Employee ID] = r2.[Employee ID]
WHERE (
(r2.[Assignment Start Date] BETWEEN r1.[Assignment Start Date] and r1.[Assignment End Date])
or
(r2.[Assignment End Date] between p1.[Assignment Start Date] and p1.[Assignment End Date])
)
AND r1.PK <> r2.PK