SQL 分组统计增加小计和汇总 group by rollup group by cube

一、group by rollup其实就是在group by的基础上做了一个合计

SQL 中ROLLUP 用法
ROLLUP 运算符生成的结果集类似于 CUBE 运算符生成的结果集。

下面是 CUBE 和 ROLLUP 之间的具体区别:

1、CUBE 生成的结果集显示了所选列中值的所有组合的聚合。
2、ROLLUP 生成的结果集显示了所选列中值的某一层次结构的聚合。

ROLLUP 优点:

(1)ROLLUP 返回单个结果集,而 COMPUTE BY 返回多个结果集,而多个结果集会增加应用程序代码的复杂性。
(2)ROLLUP 可以在服务器游标中使用,而 COMPUTE BY 则不可以。
(3)有时,查询优化器为 ROLLUP 生成的执行计划比为 COMPUTE BY 生成的更为高效。

ROLLUP 用法 例一:
 -- 数据库中用户表各类型字段个用和总用户表字段个数
  select types.name as ctype,Count(columns.name)
    from sys.columns as columns left join sys.objects as objects
                  on columns.object_id = objects.object_id 
               left join sys.types as types
                  on columns.system_type_id = types.system_type_id 
    where objects.type  = 'U' -- 返回用户表
    group by types.name with rollup

进化,再增加一个分组字段,例二:
 -- 增加表名字段
 -- 数据库中用户表各表中各类型字段个数和字段总个数
  select objects.name as ctablicname , types.name as ctype, Count(columns.name) as icount
    from sys.columns as columns left join sys.objects as objects
                  on columns.object_id = objects.object_id 
               left join sys.types as types
                  on columns.system_type_id = types.system_type_id 
    where objects.type  = 'U' -- 返回用户表
    group by objects.name , types.name 
    with rollup

二、同时取出明细 with cube

例三:同时取出明细
     -- 数据库中用户表各表中各类型字段个数和明细
  select objects.name ,types.name as ctype, Count(columns.name) as icount
    from sys.columns as columns left join sys.objects as objects
                  on columns.object_id = objects.object_id 
               left join sys.types as types
                  on columns.system_type_id = types.system_type_id 
    where objects.type  = 'U' -- 返回用户表
    group by objects.name , types.name 
    with cube

进化,Grouping() 增加一个分组标记, 例四:
  -- 数据库中用户表各表中各类型字段个数和明细
     -- Grouping():判断是否是分组的列,1表示聚合列,0表示不是
     
  select Grouping(objects.name) bGroup , objects.name ,types.name as ctype, Count(columns.name) as icount
    from sys.columns as columns left join sys.objects as objects
                  on columns.object_id = objects.object_id 
               left join sys.types as types
                  on columns.system_type_id = types.system_type_id 
    where objects.type  = 'U' -- 返回用户表
    group by objects.name , types.name 
    with cube 
    

你可能感兴趣的:(SQL)