您的 Db2 平台是什么?
如果你只想要总行数,那么
select count(*)
from mytable
如果您想要按名称加上总数的小计,SQL 最初并不支持。您必须合并这两个结果。
select name, count(*) as cnt
from mytable
group by name
UNION ALL
select '', count(*)
from mytable
不过,更现代的版本添加了ROLLUP(和CUBE)功能...
select name, count(*) as cnt
from mytable
group by name with rollup
编辑
要为 name 设置值,您可以简单地使用 COALESCE() 假设 name 除了在总行中之外永远不会为空。
select coalesce(name,'-Total-') as name, count(*) as cnt
from mytable
group by name with rollup
更正确的方法是使用GROUPING()函数
要么只返回标志
select name, count(*) as cnt, grouping(name) as IS_TOTAL
from mytable
group by name with rollup
或者用它来设置文字
select case grouping(name)
when 1 then '-Total-'
else name
end as name
, count(*) as cnt
from mytable
group by name with rollup
包括总数
要包括每一行的总数,你可以这样做......
with tot as (select count(*) as cnt from mytable)
select name
, count(*) as name_cnt
, tot.cnt as total_cnt
from mytable
cross join tot
group by name
请注意,这将读取 mytable 两次,一次用于总计,另一次用于详细行。但很明显你在做什么。
另一种选择是这样的
with allrows as (
select name, count(*) as cnt, grouping(name) as IS_TOTAL
from mytable
group by name with rollup
)
select dtl.name, dtl.cnt, tot.cnt
from allrows dtl
join allrows tot
on tot.is_total = 1
where
dtl.is_total = 0