如何使用 having 子句从 DB2 中获取 count(*) total?

How to get count(*) total from DB2 with having clause?

如何在 DB2 中使用 group by 子句获取所有 return 行的总和?

例如:

描述中心 ---- --- 碗 30 图 21 勺子 6 总和 57

SELECT COUNT (name) as Desc, Count(*) OVER ALL 按名称分组

以上查询来自 DB2 的 return 错误。 return 所有行的 SUM 的正确 SQL 语句是什么?

谢谢, 布兰登.

试试这个查询, select 名称,计数 (*) 来自 table 按名称分组

你的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()函数
return 只是标志

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