天天看点

实现数据分类汇总的SQL语句

现有表Test,内容如下: 

ID   Catalog    Num 
1          A            3 
1          B            5
2          A            8 
2          B            2      

现在想按ID查询出这种结果:

-------------------- 
1          A           3
1          B           5 
汇总小计:      8
2          A           8 
2          B           2 
汇总小计:     10      

问:该如何实现?

在生成包含小计和合计的报表时,ROLLUP 运算符很有用。ROLLUP 运算符生成的结果集类似于 CUBE 运算符所生成的结果集。

========================

CUBE 运算符生成的结果集是多维数据集。多维数据集是事实数据的扩展,事实数据即记录个别事件的数据。扩展建立在用户打算分析的列上。这些列被称为维。多维数据集是一个结果集,其中包含了各维度的所有可能组合的交叉表格。

CUBE 运算符在 SELECT 语句的 GROUP BY 子句中指定。该语句的选择列表应包含维度列和聚合函数表达式。GROUP BY 应指定维度列和关键字 WITH CUBE。结果集将包含维度列中各值的所有可能组合,以及与这些维度值组合相匹配的基础行中的聚合值。

========================= 

CUBE 和 ROLLUP 之间的区别在于: 

CUBE 生成的结果集显示了所选列中值的所有组合的聚合。

ROLLUP 生成的结果集显示了所选列中值的某一层次结构的聚合。

The ROLLUP operator is useful in generating reports that contain subtotals and totals. The ROLLUP operator generates a result set that is similar to the result sets generated by the CUBE operator.

The differences between CUBE and ROLLUP are:

  • CUBE generates a result set showing aggregates for all combinations of values in the selected columns.
  • ROLLUP generates a result set showing aggregates for a hierarchy of values in the selected columns.
ELSE ISNULL(ID, 'UNKNOWN') 
       END AS ID, 
       CASE WHEN (GROUPING(Catalog) = 1) THEN 'ALL' 
            ELSE ISNULL(Catalog, 'UNKNOWN') 
       END AS Catalog, 
       SUM(Num) AS Num 
FROM Test 
GROUP BY ID, Catalog WITH ROLLUP