如何在一个查询中获得不同条件下的总和?

时间:2014-04-29 16:47:54

标签: sql aggregate-functions informix

如何在一个查询中执行以下操作:

如果我有两个这样的查询

SELECT SUM(value +sal) AS sump
FROM loans 
WHERE active_flag = 1

SELECT SUM(value +sal) AS sumn
FROM loans 
WHERE active_flag = 2

我希望在同一个查询中获得sumpsumn

1 个答案:

答案 0 :(得分:5)

SELECT SUM(CASE 
             WHEN active_flag = 1 THEN value + sal 
             ELSE 0 
           END) AS sump,
       SUM(CASE 
             WHEN active_flag = 2 THEN value + sal 
             ELSE 0 
           END) AS sumn 
FROM   loans 
WHERE  active_flag IN ( 1, 2 )