对于以下逻辑,如何在SQL Server中编写CASE语句?

时间:2018-09-05 01:39:44

标签: sql-server case

我有这样的SQL查询:

With Net as 
(
    Select 
        C.region, C.Project_number, C.Country_Name, C.currency_rate, 
        C.snapshot_date, C.H12_LC, C.F12_LC, C.Sales_LC, C.Net_NCC_Cost
    From 
        (
           .......
        )    
)
select 
    region,
    Project_number,
    Country_Name,
    currency_rate,
    snapshot_date,
    isnull(sum(H12_LC), 0) H12_LC,
    isnull(sum(F12_LC), 0) F12_LC,
    isnull(sum(Sales_LC), 0) Sales_LC,
    Net_NCC_Cost
from 
    Net 
group by 
    Net.region, Net.project_number, Net.Country_Name,

我应该如何以及在何处包括逻辑上的case语句:

Total_NCC = [Net_NCC_Cost])+ (IF( (H12 - F12) > 0, -(H12 - F12)*1000000, (-H12 + F12)*1000000))) 

谢谢

鲍勃

1 个答案:

答案 0 :(得分:0)

案例expressions只是实现布尔逻辑的一些单词,即类似于if的用法,但带有单词。

SELECT
    region
  , Project_number
  , Country_Name
  , currency_rate
  , snapshot_date
  , ISNULL(SUM(H12_LC), 0)   h12_lc
  , ISNULL(SUM(F12_LC), 0)   f12_lc
  , ISNULL(SUM(Sales_LC), 0) sales_lc
  , Net_NCC_Cost
  , [Net_NCC_Cost] 
    + CASE
          WHEN (H12 - F12) > 0 THEN -(H12 - F12) * 1000000
          ELSE (-H12 + F12) * 1000000
      END AS Total_NCC
FROM yourtable

ps:expression的值是一个单一的值,statement的计算要复杂得多