如何在DB2中使用group by子句获取所有返回行的总和?
例如:
Desc Ctr ---- --- 碗30 板21 勺子6 总和57
SELECT COUNT(name)为Desc,Count(*)OVER ALL GROUP BY名称
以上查询从DB2返回错误。返回所有行的SUM的正确SQL语句是什么?
谢谢, 布兰登。
答案 0 :(得分:0)
尝试此查询, 从名称
的表组中选择名称,计数(*)答案 1 :(得分:0)
你的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()
,假设除了总行外,名称不会为null。
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
Inculde total
要在每一行中包含总数,您可以这样做......
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