我正在使用CASE語句來計算溢價和結果是如果我只是使用SELECT SUM語句的方式。爲什麼會這樣?爲什麼我通過使用CASE語句有不同的結果?
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
總和會是但現在,如果我用這個:
select sum(premium)
from Test_Plaza_ProductionReport
where PolicyType in ('New Business','Renewal','Rewrite')
and Year(EffectiveDate)=2016
現在總和 它的200萬斷!這怎麼可能?
在條件中看不到任何重疊,但基數據中是否有負值 –
John,是的,我的確有負值。我也必須考慮到它們。 – Oleg
那麼,爲了將它們考慮在內,我應該如何使用? – Oleg