2014-10-04 69 views
0

我正在使用這裏顯示的查詢來總結財務目標第一條語句(expd)正在工作正常,它顯示的總和在socode不等於29和42。但是 第二個陳述我只想得到總和socode = 42和29和20,但它給出0.00值,而29和42有它自己的價值。如何使用SQL case語句獲取總和值

select 
    isnull(CONVERT(DECIMAL(10, 2), 
      SUM(CASE WHEN SoCode <> 42 and SoCode <> 29 and SoCode <> 20 
         THEN (Financialtarget)/100000 ELSE 0 END)), 0) as expd, 
    isnull(CONVERT(DECIMAL(10, 2), 
      SUM(CASE WHEN (SoCode = 29) and (SoCode = 42) 
         THEN (Financialtarget)/100000 ELSE 0 END)), 0) as expd1 
from 
    MPR 
where 
    month <= 7 
    and mpryear = '2014-15' 
    and Division = '12' 

感謝

+0

請格式化代碼。 – artm 2014-10-04 11:16:03

回答

3

expd1是0,因爲條件(SoCode=29) and (SoCode=42)永遠是錯的。它應該是使用OR(SoCode=29) OR (SoCode=42) OR (SOCode=20),而不是使用AND

SELECT 
    ISNULL(CONVERT(DECIMAL(10,2), 
    SUM(CASE WHEN SoCode <> 42 AND SoCode <> 29 AND SoCode <> 20 
     THEN (Financialtarget)/100000 
     ELSE 0 END)),0) AS expd, 
    ISNULL(CONVERT(DECIMAL(10,2), 
     SUM(CASE WHEN (SoCode = 29) OR (SoCode = 42) OR (SOCode = 20) 
     THEN (Financialtarget)/100000 
     ELSE 0 END)),0) AS expd1 
FROM MPR 
WHERE month <= 7 AND mpryear = '2014-15' AND Division = '12' 

另外,您還可以使用IN

SELECT 
    ISNULL(CONVERT(DECIMAL(10,2), 
    SUM(CASE WHEN SoCode <> 42 AND SoCode <> 29 AND SoCode <> 20 
     THEN (Financialtarget)/100000 
     ELSE 0 END)),0) AS expd, 
    ISNULL(CONVERT(DECIMAL(10,2), 
     SUM(CASE WHEN SoCode IN (29,42,20) 
     THEN (Financialtarget)/100000 
     ELSE 0 END)),0) AS expd1 
FROM MPR 
WHERE month <= 7 AND mpryear = '2014-15' AND Division = '12' 
+0

謝謝親愛的工作.............. – 2014-10-07 04:40:02

+0

不客氣,請接受我的答案,如果它解決了你的問題。請參閱此處瞭解更多詳情:http://meta.stackexchange.com/a/5235/255183 – ekad 2014-10-07 05:32:55