我正在处理一个SQL查询,该查询将在ServiceStart和ServiceEnd与该提供程序的另一个条目重叠时组合信息。在大多数情况下,查询是有效的,但是,我得到了很多NULL行。
我认为这可能与使用OUTER APPLY有关。但是,将外部应用程序更改为交叉应用程序也不起作用。我还尝试在查询中指定WHERE ServiceID不为NULL。两种方法的结果都是相同的。在下面,我提供了当前返回结果的屏幕快照,以及带有完整代码的rextester.com链接。
DECLARE @StartTime DATETIME, @EndTime DATETIME
SET @StartTime = '2018-11-01'
SET @EndTime = '2018-11-05'
;WITH cte
AS (SELECT c.ClaimID,
c.ProvidedBy,
c.StartTime,
c.EndTime,
oa.ServiceStart,
oa.ServiceEnd,
c.ClaimDetailID,
c.ServiceID,
c.Duration
FROM tbl_Claims c
OUTER APPLY
(
SELECT MIN(t2.StartTime) ServiceStart,
MAX(t2.EndTime) ServiceEnd
FROM tbl_Claims t2
WHERE t2.StartTime <= c.EndTime
AND (t2.EndTime >= c.StartTime)
AND (t2.ServiceID <> 0 and c.ServiceID <> 0)
AND (t2.StartTime >= @StartTime AND t2.EndTime <= @EndTime)
AND (t2.ProvidedBy = c.ProvidedBy)
) oa)
SELECT c.ProvidedBy,
c.ServiceStart,
c.ServiceEnd,
MAX(ca1.ClaimIDs) ClaimIDs,
MAX(ca2.ClaimDetailIDs) ClaimDetailIDs,
MAX(ca3.ServiceIDs) ServiceIDs
FROM cte c
CROSS APPLY
(
SELECT STUFF(
(
SELECT ', ' + CAST(p.[ClaimID] AS VARCHAR(40))
FROM cte AS p
WHERE p.ServiceStart = c.ServiceStart AND (p.ProvidedBy = c.ProvidedBy)
AND p.ServiceID <> 0
ORDER BY p.ClaimID FOR XML PATH('')
), 1, 1, '')
) ca1(ClaimIDs)
CROSS APPLY
(
SELECT STUFF(
(
SELECT ', ' + CAST(p.[ClaimDetailID] AS VARCHAR(40))
FROM cte AS p
WHERE p.ServiceStart = c.ServiceStart AND (p.ProvidedBy = c.ProvidedBy)
AND p.ServiceID <> 0
ORDER BY p.ClaimDetailID FOR XML PATH('')
), 1, 1, '')
) ca2(ClaimDetailIDs)
CROSS APPLY
(
SELECT STUFF(
(
SELECT ', ' + CAST(p.[ServiceID] AS VARCHAR(40))
FROM cte AS p
WHERE p.ServiceStart = c.ServiceStart AND (p.ProvidedBy = c.ProvidedBy)
AND p.ServiceID <> 0
ORDER BY p.ClaimDetailID FOR XML PATH('')
), 1, 1, '')
) ca3(ServiceIDs)
GROUP BY c.ProvidedBy,
c.ServiceStart,
c.ServiceEnd
ORDER BY c.ProvidedBy,
c.ServiceStart,
c.ServiceEnd;