有没有办法在使用GROUPING SETS时强制汇总行到结果集的底部?

时间:2014-05-30 19:08:59

标签: sql tsql

除了在ORDER BY子句中计算汇总行并最终在结果集的顶部以外,以下工作完美无缺。无论如何强制它到底而不删除ORDER BY子句?

select 
  col1,sum(col2),sum(col3) as [Count] FROM #tmpTbl 
where 
  col3>0 
group by 
  grouping sets((col1),()) 
order by 
  [Count] desc

1 个答案:

答案 0 :(得分:2)

我不确定您的查询实际上是如何正常运行的,但您需要在Order By子句中添加条件:

Select      col1,
            sum(col2),
            sum(col3) as [Count] 
From        #tmpTbl 
Where       [Count] > 0 
Group by    Grouping Sets((col1),()), 
Order by    Grouping(col1),
            [Count] desc

但是,没有语法错误的查询将是这样的:

Select      col1,
            sum(col2),
            sum(col3) as [Count] 
From        #tmpTbl 
Group by    Grouping Sets((col1),())
Having      Sum(col3)  > 0 
Order by    Grouping(col1),
            [Count] desc

基本上,Grouping(column)返回1或0,具体取决于当前行是否正在分组。您只需传入集合中的任何列即可获得此结果。在这种情况下,col1。不是分组行的所有内容都将得到0,分组行将得到1,导致摘要行最后排序。

只是为了好玩:如果您希望摘要列显示“总计”...

Select      Case When Grouping(col1) = 1 Then 'Total' Else Cast(col1 As Varchar(5)) End As Col1,
            sum(col2),
            sum(col3) as [Count] 
From        #tmpTbl 
Group by    Grouping Sets((col1),())
Having      Sum(col3)  > 0 
Order by    Grouping(col1),
            [Count] desc