如何获得结果集中的行总和?

时间:2014-07-21 17:19:35

标签: sql postgresql aggregate-functions common-table-expression union-all

我在PostgreSQL中编写以下查询:

select case mod(empno,2)
        when 0 then 'EVEN '
        else 'ODD  '
       end as empno, sum(sal)
from emp
group by mod(empno,2);

获得输出:

EMPNO   SUM(SAL)
EVEN       25
ODD        50

如何将查询修改为输出,如下所示?

EMPNO   SUM(SAL)
EVEN       25
ODD        50
Total      75

2 个答案:

答案 0 :(得分:1)

您可以执行以下UNION ALL

select case mod(empno,2)
when 0 then 'EVEN '
else 'ODD  '
end as empno, sum(sal)
from emp
group by mod(empno,2)

UNION ALL

select 'TOTAL' as empno, 
sum(sal)
from emp

答案 1 :(得分:0)

重复使用结果计算附加到行的总和通常更便宜。为此,我建议CTE

WITH cte AS (
   SELECT CASE WHEN empno % 2 = 0
            THEN 'EVEN '
            ELSE 'ODD  '
          END AS empno
        , sum(sal)::int AS sum_sal
   FROM   emp
   GROUP  BY 1
   )
SELECT *
FROM   cte

UNION ALL
SELECT 'Total ', sum(sum_sal)::bigint
FROM   cte;

对于查询而言,这并不像示例中那样微不足道,但这可能是一种简化。