首页 > 开发 > 综合 > 正文

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

2024-07-21 02:05:34
字体:
来源:转载
供稿:网友

现有表test,内容如下: id   catalog    num 1          a            3 1          b            52          a            8 2          b            2 现在想按id查询出这种结果: -------------------- 1          a           31          b           5 汇总小计:      82          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.
最后查询语句如下:

select case when (grouping(id) = 1) then 'all'             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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表