Scope
Wouldn’t it be nice to let SQL layer to handle all the aggregations and just bind the whole datasource to a .Net control and display as is?
Let’s see how it was done.
Steps
This was achieved by using GROUPING and ROLLUP (will talk about it at the end).
As you can see, GROUPING indicated in the resultset as if the columns were calculated by the SQL Server and is not part of the normal aggregation result set.
As you may now wonder, if I group another column, it will show as 1 too, because that is the total of everything.
This is the final code of how things were done.
Pay attention to on how ROLLUP is applied to the GROUP BY. Combining HAVING and GROUPING, you will then get the desired sub total or grand total of the column values.
select QuestionId , QuestionType , QuestionNumber, ISNULL(QuestionDesc, 'Total') as QuestionDesc , Question, SUM([Weight]) as [Weight] , Grouping(QuestionId) AS GroupingQuestionId , Grouping(QuestionType) AS GroupingQuestionType from ( -- snipped ) Derived group by rollup(QuestionId, QuestionNumber, QuestionDesc, Question, [Weight], QuestionType) having Grouping(QuestionType) = 0 or (Grouping(QuestionId) = 1 and Grouping(QuestionType) = 1 and .........)
No comments:
Post a Comment