0

我有一个查询,我在其中计算任何给定客户每月的不同索赔数量,以获得 YTD 报告。但我发现如果客户在这一年没有任何索赔(所以每个月都应该显示为 0),那么客户根本不会出现在结果集中。我需要客户显示该月的计数为“0”。有谁知道如何做到这一点?感谢您的帮助!:)

我的查询类似于:

Select c.client_name,
   SUM(CASE DATEPART(MONTH,c2.DateField)WHEN 1 THEN 1 ELSE 0 END) AS [Jan-13],
   SUM(CASE DATEPART(MONTH,c2.DateField)WHEN 2 THEN 1 ELSE 0 END) AS [Feb-13],
   SUM(CASE DATEPART(MONTH,c2.DateField)WHEN 3 THEN 1 ELSE 0 END) AS [Mar-13] etc.....
   From Client c (Nolock)
          inner join claim c2 (nolock)
          on c.client_id = c2.client_id
   Where c.client_id IN (1,3,4,5,7) AND
   c2.DateField between '001-01-2013' and Getdate()
   GROUP BY c.client_name
   ORDER BY c.Client_name

我的结果如下:

Client Name|Jan-13|Feb-13|Mar-13|etc.....
abc company|12    |17    |0     |etc......
zzz company|3     |0     |15    |etc...

我需要结果看起来像:

Client Name|Jan-13|Feb-13|Mar-13|etc.....
abc company|12    |17    |0     |etc......
rad company|0     |0     |0     |etc.....
zzz company|3     |0     |15    |etc...
4

2 回答 2

0

只有当索赔表中有匹配的记录时,您正在使用inner join它将返回客户表中的记录,将其替换为它将left outer join根据 WHERE 子句为您提供客户表中的所有记录,并加入索赔表中的列。

此查询将加入然后过滤。

Select c.client_name,
   SUM(CASE DATEPART(MONTH,c2.DateField)WHEN 1 THEN 1 ELSE 0 END) AS [Jan-13],
   SUM(CASE DATEPART(MONTH,c2.DateField)WHEN 2 THEN 1 ELSE 0 END) AS [Feb-13],
   SUM(CASE DATEPART(MONTH,c2.DateField)WHEN 3 THEN 1 ELSE 0 END) AS [Mar-13] 
   etc.....
   From Client c (Nolock)
          left outer join claim c2 (nolock)
          on c.client_id = c2.client_id
   Where c.client_id IN (1,3,4,5,7) AND
   ( c2.DateField between '01-01-2013' and Getdate() OR c2.DateField IS NULL )
   GROUP BY c.client_name
   ORDER BY c.Client_name

或此查询将在之前过滤声明行 -

Select c.client_name,
   SUM(CASE DATEPART(MONTH,c2.DateField)WHEN 1 THEN 1 ELSE 0 END) AS [Jan-13],
   SUM(CASE DATEPART(MONTH,c2.DateField)WHEN 2 THEN 1 ELSE 0 END) AS [Feb-13],
   SUM(CASE DATEPART(MONTH,c2.DateField)WHEN 3 THEN 1 ELSE 0 END) AS [Mar-13] 
   etc.....
   From Client c (Nolock)
          left outer join claim c2 (nolock)
          on c.client_id = c2.client_id 
              AND c2.DateField between '01-01-2013' and Getdate()
   Where c.client_id IN (1,3,4,5,7)
   GROUP BY c.client_name
   ORDER BY c.Client_name
于 2013-09-08T22:23:38.763 回答
0

这可能有效

Select
    c.client_name,
    Sum(Case Month(c2.DateField) When 1 Then 1 Else 0 End) As [Jan-13],
    Sum(Case Month(c2.DateField) When 2 Then 1 Else 0 End) As [Feb-13],
    Sum(Case Month(c2.DateField) When 3 Then 1 Else 0 End) As [Mar-13],...
From 
    Client c With (Nolock)
        left outer join 
    Claim c2 With (nolock)
        On c.client_id = c2.client_id And
           c2.DateField between '01-01'2013' and GetDate() -- putting it here makes the outer join apply after the filter
Where 
    c.client_id IN (1,3,4,5,7)
Group By
    c.client_name
Order By 
    c.Client_name

如果不是,您需要在过滤声明的子查询上保留外部联接。无论哪种方式,诀窍都是确保在外部表上的过滤器之后应用左外连接。

于 2013-09-08T23:00:06.337 回答