9

我正在尝试显示一行“总计”,它将对 Count 列进行总和。下面的代码将有两列,Environment 和 Count。

select 
case 
when env is null THEN 'Unknown' 
else env
end,
count(*) as Count
from env_table
group by env
order by env
/

我想要的输出:

视窗 200

Linux 120

总计 320

正如您在上面看到的,我想做的是在最后添加一个名为“Total”的行,它实际上会执行 SUM(count(*))。执行此操作的正确语法是什么?谢谢!

4

5 回答 5

27

使用WITH ROLLUP修饰符GROUP BY

SELECT   IFNULL(env, 'Unknown'),
         COUNT(*) AS Count
FROM     env_table
GROUP BY env WITH ROLLUP
ORDER BY env
于 2012-05-03T14:54:10.107 回答
5

也许是这样的?

SELECT   IFNULL(env, 'Unknown'),
         COUNT(*) AS Count
FROM env_table
GROUP BY env
ORDER BY env
UNION ALL
SELECT   null,
         Count(*)
FROM env_table
于 2012-05-03T14:55:14.893 回答
1
SELECT   COALESCE(env, 'Total') AS Description,
         COUNT(*) AS Count
FROM     env_table
GROUP BY env WITH ROLLUP
ORDER BY env
于 2015-08-21T14:41:23.053 回答
0
SELECT env, count 
  FROM (SELECT CASE WHEN env is null THEN 'Unknown' ELSE env END env,
               count(*) count
          FROM env_table
         GROUP BY env
      ORDER BY env)
UNION ALL
SELECT 'Total' env,
       count(*) count
  FROM env_table       
于 2012-05-03T15:03:57.590 回答
0

我希望它有效。以防万一,如果需要任何更正,很想听听我的错误。

select environment, count from table a
union all
(select "total" as environment, sum(count) from table b
group by 1)
于 2021-06-26T12:11:12.710 回答