現(xiàn)有表test,內(nèi)容如下: id catalog num 1 a 3 1 b 52 a 8 2 b 2 現(xiàn)在想按id查詢出這種結(jié)果: -------------------- 1 a 31 b 5 匯總小計: 82 a 8 2 b 2 匯總小計: 10 問:該如何實現(xiàn)?
在生成包含小計和合計的報表時,rollup 運算符很有用。rollup 運算符生成的結(jié)果集類似于 cube 運算符所生成的結(jié)果集。 ======================== cube 運算符生成的結(jié)果集是多維數(shù)據(jù)集。多維數(shù)據(jù)集是事實數(shù)據(jù)的擴展,事實數(shù)據(jù)即記錄個別事件的數(shù)據(jù)。擴展建立在用戶打算分析的列上。這些列被稱為維。多維數(shù)據(jù)集是一個結(jié)果集,其中包含了各維度的所有可能組合的交叉表格。 cube 運算符在 select 語句的 group by 子句中指定。該語句的選擇列表應(yīng)包含維度列和聚合函數(shù)表達(dá)式。group by 應(yīng)指定維度列和關(guān)鍵字 with cube。結(jié)果集將包含維度列中各值的所有可能組合,以及與這些維度值組合相匹配的基礎(chǔ)行中的聚合值。 ========================= cube 和 rollup 之間的區(qū)別在于: cube 生成的結(jié)果集顯示了所選列中值的所有組合的聚合。 rollup 生成的結(jié)果集顯示了所選列中值的某一層次結(jié)構(gòu)的聚合。
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