如何排除一个值并使具有该值的所有内容都不在计算中

时间:2016-11-14 17:13:52

标签: sql-server tsql reporting-services

一个Policy Number可以有多个不同的ClassCode,只有一个Premium的总金额。在我的SSRS报告中,我希望能够创建参数ClassCode,如果我排除(取消选中)至少其中一个ClassCode,则整个保单的政策编号不需要在计算中。 可以说,如果我要排除ClassCode 58,则1,644.00的Premium不应该出现在我的报告中。

enter image description here

我试图在我的查询AND ClassCode <> 58中说,但它只排除了一行并保留了Premium。但我的目标是排除所有内容,如果它有ClassCode 58。

SELECT policynumber,
       classcode,
       /*
       Using ROW_NUMBER() to check if it's the first record in the join and returns the Premium value if so, otherwise it will display 0. 
       The ORDER BY (SELECT 0) is there just because I don't need the row number to be based on any explicit order.
       */
       CASE
         WHEN ROW_NUMBER()
                OVER (
                  PARTITION BY cte1.policynumber
                  ORDER BY (SELECT 0)) = 1 THEN premium
         ELSE 0
       END        AS Premium,
       c.yearnum  TransEffYearNum,
       c.monthnum TransEffMonthNum
FROM   cte1
       INNER JOIN cte2
               ON cte1.policynumber = cte2.policynumber
       RIGHT JOIN tblcalendar c
               ON c.yearnum = Year(cte1.policyeffectivedate)
                  AND c.monthnum = Month(cte1.policyeffectivedate)
WHERE  c.yearnum = 2016
       AND classcode <> 58  

2 个答案:

答案 0 :(得分:0)

您应首先排除所有具有您要设置的ClassCode的政策号。 而不是 where c.YearNum = 2016 AND ClassCode <> 58

使用

where  PolicyNumber NOT IN
(SELECT  PolicyNumber 
 From cte1 inner join cte2 on cte1.PolicyNumber=cte2.PolicyNumber
 WHERE ClassCode = 58);

那应该这样做。

答案 1 :(得分:0)

如果你想要消除政策3的所有行,这可能会有效。

SELECT policynumber,
       classcode,
       /*
       Using ROW_NUMBER() to check if it's the first record in the join and returns the Premium value if so, otherwise it will display 0. 
       The ORDER BY (SELECT 0) is there just because I don't need the row number to be based on any explicit order.
       */
       CASE
         WHEN ROW_NUMBER()
                OVER (
                  PARTITION BY cte1.policynumber
                  ORDER BY (SELECT 0)) = 1 THEN premium
         ELSE 0
       END        AS Premium,
       c.yearnum  TransEffYearNum,
       c.monthnum TransEffMonthNum
FROM   cte1
       INNER JOIN cte2
               ON cte1.policynumber = cte2.policynumber
       RIGHT JOIN tblcalendar c
               ON c.yearnum = Year(cte1.policyeffectivedate)
                  AND c.monthnum = Month(cte1.policyeffectivedate)
WHERE  c.yearnum = 2016
       AND cte2.policynumber NOT IN (SELECT policynumber FROM cte2 WHERE ClassCode = 58 and policynumber IS NOT NULL);