SqlServer-ROLLUP

在生成包含小記和合計的報表時,ROLLUP運算符很有用,ROLLUP運算符生成的結果集類似於CUBE運算符所生成的結果集.

ROLLUP和CUBE的區別在於:

1. cube生成的結果集顯示了所選列的所有組合的聚合

2. rollup生成的結果集顯示了所選列中值的某一個層次結構的聚合

示例:

Sql:

With rollup:

select case when(grouping(sex)=1) then '合計' else sex end,

case when(grouping(sclass)=1) then '合計' else sclass end,

sum(score) '合計'

from student

group by sex,sclass with rollup

With cube

select case when(grouping(sex)=1) then '小記' else sex

end as 性別,

case when(grouping(sclass)=1) then '小記' else sclass

end as 班級,

sum(score)

from student

group by sex,sclass with cube

區別解釋:

1. cube操作爲所選的列的所有組合做了彙總, 男/2,男/3,男/小記,女/2,女/3,女/小記,小記/小記,小記/2,小記/3

2. rollup操作並不針對多列中的所有可能進行彙總,而是以左邊的列爲主,列出右邊的所有可能,然後彙總,不會針對右邊的列,將左邊列的所有彙總可能計算出來.

優點:

1. rollup返回單個結果集,而compute by返回多個結果集,多個結果集會增加代碼的複雜性

2. rollup可以在服務器遊標中使用,compute by不可以

3. rollup比compute by 執行起來更加高效

通過排序,可以實現系統想要的效果,

可以將小記彙總放在最上面,也可以將小記彙總放在各個分組之上.

例如:

select case when(grouping(sex)=1) then '合計' else sex end,

case when(grouping(sclass)=1) then '合計' else sclass end,

sum(score) '合計'

from student

group by sex,sclass with rollup

order by grouping(sex) desc,grouping(sclass) desc,sex

select case when(grouping(sex)=1) then '合計' else sex end,

case when(grouping(sclass)=1) then '合計' else sclass end,

sum(score) '合計'

from student

group by sex,sclass with rollup

order by grouping(sex) desc,sex,grouping(sclass) desc

出處:http://www.cnblogs.com/oneword/archive/2009/04/28/1445201.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章