在 Oracle 数据库中,我们经常需要对查询结果中的特定列进行统计汇总,例如计算某一列的总和,并将这个汇总值作为一个新的行添加到查询结果的末尾。这可以通过使用 SQL 中的 ROLLUP
功能来实现,下面是一个具体的例子:
SELECT
CASE WHEN text IS NOT NULL THEN text ELSE '总计' END text,
CASE WHEN text IS NOT NULL THEN id ELSE 0 END id,
SUM(total_num) AS total_num
FROM (SELECT text,
(CASE
WHEN ID = 1 THEN 1
WHEN ID = 2 THEN 2
WHEN ID = 3 THEN 4
WHEN ID = 4 THEN 4
WHEN ID = 5 THEN 5
WHEN ID = 6 THEN 4
WHEN ID = 7 THEN 4
END) id,
SUM(total_num) total_num
FROM (SELECT aa.id, aa.text, 1 total_num
FROM (SELECT 1 id,'AAA' text FROM dual
UNION
SELECT 2 id,'BBB' text FROM dual
UNION
SELECT 3 id,'CCC' text FROM dual
UNION
SELECT 4 id,'CCC' text FROM dual
UNION
SELECT 6 id,'CCC' text FROM dual
UNION
SELECT 7 id,'CCC' text FROM dual
UNION
SELECT 5 id,'DDD' text FROM dual
)aa
)
GROUP BY text,(CASE
WHEN id = 1 THEN 1
WHEN id = 2 THEN 2
WHEN id = 3 THEN 4
WHEN id = 4 THEN 4
WHEN id = 5 THEN 5
WHEN id = 6 THEN 4
WHEN id = 7 THEN 4
END)
ORDER BY id
) A
GROUP BY rollup(text,id)
HAVING text IS NULL OR id IS NOT NULL