0

I am using the query shown here to sum of financial target first statement(expd) is working fine it's showing sum where socode is not equal to 29 and 42. But the second statement I want to get sum only where socode = 42 and 29 and 20 but its giving 0.00 value while 29 and 42 having its own value.

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' 

Thanks

1
  • Please format the code. Commented Oct 4, 2014 at 11:16

1 Answer 1

3

expd1 is 0 because the condition (SoCode=29) and (SoCode=42) is always wrong. It should be using OR like (SoCode=29) OR (SoCode=42) OR (SOCode=20) instead of using 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' 

Alternatively you can also use 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' 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.