T-SQL查询使用APPLY运算符返回NULL行

时间:2019-01-18 14:57:43

标签: sql-server sql-server-2016

我正在处理一个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;
  • 问题是:我正在返回空行,如图here
  • 期望的结果是:如图here所示,其中包含完整的代码。

0 个答案:

没有答案