【发布时间】:2016-06-15 00:32:05
【问题描述】:
我正在使用 CASE 语句来计算溢价,如果我只使用 SELECT SUM 语句,结果会很差。为什么会这样?
select
SUM(CASE WHEN Premium > 0 and Premium <= 5000 AND Year(EffectiveDate)=2016 AND PolicyType = 'New Business' THEN Premium ELSE 0 END) as '0-5K_WP',
SUM(CASE WHEN Premium > 5000 and Premium <=10000 AND Year(EffectiveDate)=2016 AND PolicyType = 'New Business' THEN Premium ELSE 0 END) AS '5K-10K_WP',
SUM(CASE WHEN Premium > 10000 and Premium <= 25000 AND Year(EffectiveDate)=2016 AND PolicyType = 'New Business' THEN Premium ELSE 0 END) AS '10K-25K_WP',
SUM(CASE WHEN Premium > 25000 and Premium <=50000 AND Year(EffectiveDate)=2016 AND PolicyType = 'New Business' THEN Premium ELSE 0 END) AS '25K-50K_WP',
SUM(CASE WHEN Premium > 50000 AND Year(EffectiveDate)=2016 AND PolicyType = 'New Business' THEN Premium ELSE 0 END) AS '>50K_WP'
FROM Test_Plaza_ProductionReport
union all
select
SUM(CASE WHEN Premium > 0 and Premium <= 5000 AND Year(EffectiveDate)=2016 AND PolicyType = 'Renewal' THEN Premium ELSE 0 END) as '0-5K_WP',
SUM(CASE WHEN Premium > 5000 and Premium <=10000 AND Year(EffectiveDate)=2016 AND PolicyType = 'Renewal' THEN Premium ELSE 0 END) AS '5K-10K_WP',
SUM(CASE WHEN Premium > 10000 and Premium <= 25000 AND Year(EffectiveDate)=2016 AND PolicyType = 'Renewal' THEN Premium ELSE 0 END) AS '10K-25K_WP',
SUM(CASE WHEN Premium > 25000 and Premium <=50000 AND Year(EffectiveDate)=2016 AND PolicyType = 'Renewal' THEN Premium ELSE 0 END) AS '25K-50K_WP',
SUM(CASE WHEN Premium > 50000 AND Year(EffectiveDate)=2016 AND PolicyType = 'Renewal' THEN Premium ELSE 0 END) AS '>50K_WP'
FROM Test_Plaza_ProductionReport
union all
select
SUM(CASE WHEN Premium >0 and Premium <= 5000 AND Year(EffectiveDate)=2016 AND PolicyType = 'Rewrite' THEN Premium ELSE 0 END) as '0-5K_WP',
SUM(CASE WHEN Premium > 5000 and Premium <=10000 AND Year(EffectiveDate)=2016 AND PolicyType = 'Rewrite' THEN Premium ELSE 0 END) AS '5K-10K_WP',
SUM(CASE WHEN Premium > 10000 and Premium <= 25000 AND Year(EffectiveDate)=2016 AND PolicyType = 'Rewrite' THEN Premium ELSE 0 END) AS '10K-25K_WP',
SUM(CASE WHEN Premium > 25000 and Premium <=50000 AND Year(EffectiveDate)=2016 AND PolicyType = 'Rewrite' THEN Premium ELSE 0 END) AS '25K-50K_WP',
SUM(CASE WHEN Premium > 50000 AND Year(EffectiveDate)=2016 AND PolicyType = 'Rewrite' THEN Premium ELSE 0 END) AS '>50K_WP'
FROM Test_Plaza_ProductionReport
总和将是 13,286,473 但现在如果我使用这个:
select sum(premium)
from Test_Plaza_ProductionReport
where PolicyType in ('New Business','Renewal','Rewrite')
and Year(EffectiveDate)=2016
现在总和是 11,993,445 减200万!!这怎么可能?
【问题讨论】:
-
在标准中看不到任何重叠,但您在基础数据中有负值
-
约翰,是的,我确实有负值。我也必须考虑到它们。
-
那么我应该使用什么来考虑它们?
-
为负值添加一个层。我也会考虑 t tier table 让生活更轻松
-
旁白:由于
PolicyType和 year 逻辑并且对于单个case中的所有表达式都是通用的select您可以将其从表达式中删除并添加where子句:select ... from Test_Plaza_Production where PolicyType = 'New Business' and Year( EffectiveDate ) = 2016 union ....
标签: sql-server tsql reporting-services