如何在SQL Server中为下面的逻辑编写CASE语句?

问题描述 投票:0回答:1

我有这样的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))) 

谢谢

短发

sql-server case
1个回答
0
投票

Case 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是更复杂的东西

© www.soinside.com 2019 - 2024. All rights reserved.