SQL - Pivot with Grand Total Column and Row
Introduction
Microsoft SQL Server has introduced the PIVOT
and UNPIVOT
commands as enhancements to T-SQL with the release of Microsoft SQL Server 2005. Pivot Table in SQL has the ability to display data in custom aggregation. PIVOT
rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output, and performs aggregations where they are required on any remaining column values that are wanted in the final output. UNPIVOT
performs the opposite operation to PIVOT
by rotating columns of a table-valued expression into column values.
In this article, I’m concentrating on how to display Grand Total row and column for the pivot table as shown in the below grid view:
Here in the grid, I’m showing the number of matches played by a team in each month. At last, I need to show the grand total for each team (Last column) - this total gives the year count for the teams. In the same way, I need a grand total row as last row in grid, which will give the number of matches played by all the teams for that particular month.
Background
Usually as a .NET developer, first I will get the pivot table from the stored procedure to dataset and grand total row and column. I will manipulate in the C#/ VB code using Datatable
(Datatable compute method for better performance). But in this article, I want to show how to get the grand total row and column from the stored procedure, so that we can directly display data in the grid without any manipulation in the C#/VB.
How It Works
Here I’m using pivot with dynamic columns, most questions were about the column list in the PIVOT
statement. This list is fixed, but many times the new columns are determined by the report at a later stage. This problem is easily solved when we mix pivots with dynamic SQL, so here is a very simple script about how to dynamically generate the pivot
statement:
DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + colName + ']', '[' + colName + ']')
FROM Table1
WHERE Conditions
ORDER BY colName
PRINT @cols
The above script gives you the list of columns in string
format with commas. Example: [Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sept], [Oct], [Nov], [Dec]
. If you pass this dynamic query to your pivot, then your pivot columns will display dynamically.
The below SQL script creates the stored procedure which returns pivot table as output.
CREATE PROCEDURE pivot_TeamVsMatches
AS
/*First get the dynamic columns query*/
DECLARE @columnHeaders NVARCHAR (MAX)
SELECT @columnHeaders = _
COALESCE (@columnHeaders + ',[' + month + ']', '[' + month + ']')
FROM tbl_Matches
ORDER BY month
DECLARE @FinalQuery NVARCHAR(MAX)
SET @FinalQuery = ‘SELECT *
FROM
(SELECT Team,
Month
FROM tbl_Matches
) A
PIVOT
(
COUNT(*)
FOR ColName
IN (‘+@columnHeaders +’)
) B
ORDER BY Team’
PRINT ‘Pivot Queuery :’+ @FinalQuery
EXECUTE (@FinalQuery)
GO
This stored procedure returns pivot table as below:
Now to get the grand total and row, we need to form the COALESCE
query. As shown below…
/* GRAND TOTAL COLUMN */
DECLARE @GrandTotalCol NVARCHAR (MAX)
SELECT @GrandTotalCol = COALESCE (@GrandTotalCol + ‘ISNULL _
([' + CAST (Month AS VARCHAR) +'],0) + ', 'ISNULL([' + CAST(Month AS VARCHAR)+ '],0) + ')
FROM tbl_Matches ORDER BY Month
SET @GrandTotalCol = LEFT (@GrandTotalCol, LEN (@GrandTotalCol)-1)
The above query returns as below…
@GrandTotalCol = ISNULL ([' + CAST (Jan AS VARCHAR) +'],0) + ISNULL _
([' + CAST (Feb AS VARCHAR) +'],0) + ISNULL ([' + CAST (March AS VARCHAR) +'],0) + _
…………. + ISNULL ([' + CAST (Dec AS VARCHAR) +'],0).
/* GRAND TOTAL ROW */
DECLARE @GrandTotalRow NVARCHAR(MAX)
SELECT @GrandTotalRow = COALESCE(@GrandTotalRow + ',ISNULL(SUM([' + _
CAST(Month AS VARCHAR)+']),0)', 'ISNULL(SUM([' + CAST(Month AS VARCHAR)+']),0)')
FROM tbl_Matches ORDER BY Month
The above query returns as below…
@GrandTotalRow = ISNULL(SUM([' + CAST(Jan AS VARCHAR)+']),0) + _
ISNULL(SUM([' + CAST(Feb AS VARCHAR)+']),0) + ……… + _
ISNULL(SUM([' + CAST(Dec AS VARCHAR)+']),0).
The above COALESCE string
s need to be used in dynamic pivot query…
Below is the stored procedure which will give the total output of our requirement.
CREATE PROCEDURE pivot_TeamVsMatches
AS
/* COLUMNS HEADERS */
DECLARE @columnHeaders NVARCHAR (MAX)
SELECT @columnHeaders = COALESCE (@columnHeaders _
+ ',[' + month + ']', '[' + month + ']')
FROM tbl_Matches
ORDER BY month
/* GRAND TOTAL COLUMN */
DECLARE @GrandTotalCol NVARCHAR (MAX)
SELECT @GrandTotalCol = COALESCE (@GrandTotalCol + ‘ISNULL ([' + _
CAST (Month AS VARCHAR) +'],0) + ', 'ISNULL([' + CAST(Month AS VARCHAR)+ '],0) + ')
FROM tbl_Matches ORDER BY Month
SET @GrandTotalCol = LEFT (@GrandTotalCol, LEN (@GrandTotalCol)-1)
/* GRAND TOTAL ROW */
DECLARE @GrandTotalRow NVARCHAR(MAX)
SELECT @GrandTotalRow = COALESCE(@GrandTotalRow + ',ISNULL(SUM([' + _
CAST(Month AS VARCHAR)+']),0)', 'ISNULL(SUM([' + CAST(Month AS VARCHAR)+']),0)')
FROM tbl_Matches ORDER BY Month
/* MAIN QUERY */
DECLARE @FinalQuery NVARCHAR (MAX)
SET @FinalQuery = ‘SELECT *, ('+ @GrandTotalCol + ') _
AS [Grand Total] INTO #temp_MatchesTotal
FROM
(SELECT Team,
Month
FROM tbl_Matches
) A
PIVOT
(
COUNT (*)
FOR ColName
IN (‘+@columnHeaders +’)
) B
ORDER BY Team
SELECT * FROM #temp_MatchesTotal UNION ALL
SELECT ''Grand Total'','''','+@GrandTotalRow +', _
ISNULL (SUM([Grand Total]),0) FROM #temp_MatchesTotal
DROP TABLE #temp_MatchesTotal'
-- PRINT 'Pivot Query '+@FinalQuery
EXECUTE(@PivotQuery)
GO
Result as below…
Here in this stored procedure, I have used temporary table to get the grand total row. I did the UNION ALL
with temporary table; don’t forget to drop the temporary table.
For any queries & suggestions, mail me @ narapareddy.shyam@gmail.com. By using some third party controls also we can achieve this, but here I concentrated only on typical/ normal SQL query. If anybody has any efficient and different ways, kindly share with me.
Thanks again. Bye.
Post Comment
bJNoXW You made some decent factors there. I looked on the internet for the difficulty and located most people will go together with along with your website.
5IWPWO Really informative blog article.Thanks Again. Want more.
wWy6lG Wow, great blog post.Much thanks again. Keep writing.
AN8yv1 I think other web-site proprietors should take this website as an model, very clean and fantastic user genial style and design, let alone the content. You are an expert in this topic!
pj1VmO I will bookmark your blog and check once more right here regularly.
2chrVh I value the blog post.Much thanks again. Awesome.
EMVJWL Religious outlet gucci footwear. It as safe to say that they saw some one
Jlmlhv Your style is so unique in comparison to other folks I ave read stuff from. Many thanks for posting when you ave got the opportunity, Guess I will just book mark this blog.
UX4qQT victor cruz jersey have been decided by field goals. However, there are many different levels based on ability.
fjJgit I was recommended this blog by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my trouble. You are incredible! Thanks!
AlTLAH Very nice info and right to the point. I am not sure if this is in fact the best place to ask but do you people have any ideea where to get some professional writers? Thank you
V64Eqy Thank you for your blog article.Really thank you! Awesome.
jRz09q Looking forward to reading more. Great article post.
3ktYqx Thanks again for the blog post.Really looking forward to read more. Want more.
kUqguT
icAZrl Such clever work and coverage! Keep up the amazing works guys I ave added you guys to my personal
RWkauL Your style is so unique compared to other folks I have read stuff from. Thank you for posting when you have the opportunity, Guess I all just bookmark this site.
s4KVXJ Muchos Gracias for your article.Much thanks again. Great.
HYx31O Very nice post. I just stumbled upon your blog and wanted to say that I ave truly enjoyed browsing your blog posts. In any case I will be subscribing to your rss feed and I hope you write again soon!
Be2qBK I am so grateful for your blog.Much thanks again. Cool.
O7Iejq You need to participate in a contest for among the finest blogs on the web. I will advocate this website!
yVnMPQ Wow! Thank you! I always needed to write on my site something like that. Can I include a fragment of your post to my blog?
8dL0Vw Hi there, I discovered your web site via Google at the same time as searching for a similar subject, your web site got here up, it appears to be like great. I've bookmarked it in my google bookmarks.
R4Fj2q Generally I do not learn article on blogs, however I would like to say that this write-up very forced me to take a look at and do it! Your writing style has been surprised me. Thanks, quite nice post.
SpGIaL Thanks for the blog article.Really thank you! Want more.
leRY5d Spot on with this write-up, I truly think this website wants much more consideration. I'll in all probability be once more to read rather more, thanks for that info.
Dag nabbit good stuff you whsprerinappeps!
i61pWt Looking forward to reading more. Great blog. Keep writing.
SS7Y8v Awesome blog.Really looking forward to read more. Really Cool.
2G3fxD I really enjoy the post.Much thanks again. Awesome.
Related Articles:
Related Articles:
EdlDRv I cannot thank you enough for the post.Much thanks again. Much obliged.
Related Articles:
Related Articles:
Related Articles:
Related Articles:
Related Articles:
NpCVzb Major thanks for the post.Really looking forward to read more. Much obliged.
47q60F I really like and appreciate your blog post.Really looking forward to read more.
25DTnr Thanks for the blog article.Really looking forward to read more. Want more.
5fJdkZ Wow, great post.Much thanks again. Keep writing.
It is also a good idea to clean out your bag so that any lint, dirt, and other potentially damaging particles do not transfer from the inside to the outside of your bag.
Related Articles:lKb77M wow, awesome article post.Really looking forward to read more. Awesome.
6xsdbb Thanks for sharing, this is a fantastic article post.Really looking forward to read more. Great.
OPvQN5 Enjoyed every bit of your blog article.Really looking forward to read more. Cool.
qFdP0W Major thanks for the blog.Thanks Again.
8FHTDw I really enjoy the article post.Thanks Again. Will read on...
GFOqCm Really informative blog.Really thank you! Cool.
ylTYo6 I appreciate you sharing this article.Really thank you! Much obliged.