Skip to content
Advertisement

SQL : calculate multiple rows to result

How to get result table by calculate multirow?

Name     Type     Value
------------------------------
Name1    Plus     5000
Name1    Minus    1000
Name2    Plus     3000
Name2    Minus    2000

Desired result:

Name     Value(Plus-Minus) 
------------------------------
Name1    4000
Name2    1000

Advertisement

Answer

You can use conditional aggregation:

SELECT Name,
       SUM(CASE WHEN Type = 'Plus' THEN Value
                WHEN Type = 'Minus' THEN - Value
                ELSE 0
           END) as total
FROM t
GROUP BY Name;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement