我在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
答案 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;
对于查询而言,这并不像示例中那样微不足道,但这可能是一种简化。