Using the below query to get the Grand Total for Row & Column in SQL server pivot which works as expected.
But the problem is the Question No is not sorting in asc to desc or desc to asc order.
Changing this
ORDER BY sQtnNo asc
to ascending/descending don't have any effect.
/* COLUMNS HEADERS */
DECLARE @columnHeaders NVARCHAR (MAX)
SELECT @columnHeaders = COALESCE (@columnHeaders
+ ',[' + sAnsText + ']', '[' + sAnsText + ']')
FROM tblEntries
GROUP BY sAnsText
ORDER BY sAnsText
/* GRAND TOTAL COLUMN */
DECLARE @GrandTotalCol NVARCHAR (MAX)
SELECT @GrandTotalCol = COALESCE (@GrandTotalCol + 'ISNULL ([' +
CAST (sAnsText AS VARCHAR) +'],0) + ', 'ISNULL([' + CAST(sAnsText AS VARCHAR)+ '],0) + ')
FROM tblEntries
GROUP BY sAnsText
ORDER BY sAnsText
SET @GrandTotalCol = LEFT (@GrandTotalCol, LEN (@GrandTotalCol)-1)
/* GRAND TOTAL ROW */
DECLARE @GrandTotalRow NVARCHAR(MAX)
SELECT @GrandTotalRow = COALESCE(@GrandTotalRow + ',ISNULL(SUM([' +
CAST(sAnsText AS VARCHAR)+']),0)', 'ISNULL(SUM([' + CAST(sAnsText AS VARCHAR)+']),0)')
FROM tblEntries
GROUP BY sAnsText
ORDER BY sAnsText
----------------------------------------------
-- DROP TABLE temp_MatchesTotal
/* MAIN QUERY */
DECLARE @FinalQuery NVARCHAR (MAX)
SET @FinalQuery = 'SELECT *, (' + @GrandTotalCol + ')
AS [Grand Total] INTO #temp_MatchesTotal
FROM
(SELECT sQtnNo as ''Sort'',sQtnNo ,sAnsText,1 as ''Qty''
FROM tblEntries
) A
PIVOT
(
sum (Qty)
FOR sAnsText
IN (' +@columnHeaders + ')
) B
ORDER BY sQtnNo asc
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
-- SELECT @FinalQuery
EXECUTE(@FinalQuery)
Result is given below
Any suggestion will be highly helpful.
Thanks in advance.
When Using Try_Convert() Below Error Occurs
Like Is aid in the comments, your column is a varchar
, and strings don't order in the same order as a numerical value. '14'
has a lower value than '2'
and '99'
has a greater value than '843657365476547362'
.
If you want your columns to order like a numerical value, you need to treat them as a numerical value:
ORDER BY CASE Sort WHEN 'Grand Total' THEN 1 ELSE 0 END ASC, --Put Grand Total at the bottom
TRY_CONVERT(int,Sort) ASC;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.