Hello RAVI ,
I've achieved the desired order by dynamically constructing a CASE statement within the ORDER BY clause. Additionally, by including CAST(ND AS INT), the values of ND are treated as integers for proper sorting, ensuring that the final result set is ordered correctly.
DECLARE @cols NVARCHAR(MAX)=''
DECLARE @query NVARCHAR(MAX)=''
DECLARE @COLS_SUM NVARCHAR(MAX)=''
DECLARE @COLS_TOT NVARCHAR(MAX)=''
-- Preparing columns for Pivot
SELECT @cols = STUFF((SELECT ',' + ISNULL(QUOTENAME(ND), 0)
FROM (SELECT DISTINCT ISNULL(ND, 0) as ND FROM temp_days_order_pending) AS tmp
ORDER BY CAST(ND AS INT) ASC
FOR XML PATH('')), 1, 1, '')
-- Preparing sum of columns for Totals Horizontal
SELECT @COLS_SUM = @COLS_SUM + 'COALESCE(' + QUOTENAME(ND) + ', 0)+'
FROM (SELECT DISTINCT ISNULL(ND, 0) as ND FROM temp_days_order_pending ) AS tmp
SELECT @COLS_SUM = ','+ SUBSTRING(@COLS_SUM, 0, LEN(@COLS_SUM)) +' AS TOTAL'
-- Preparing sum of individual columns for Totals Vertically
SELECT @COLS_TOT = @COLS_TOT +'SUM('+ ISNULL(QUOTENAME(ND), 0) + '),'
FROM (SELECT DISTINCT ISNULL(ND, 0) as ND FROM temp_days_order_pending ) AS tmp
SELECT @COLS_TOT = SUBSTRING(@COLS_TOT, 0, LEN(@COLS_TOT))
-- Set query with dynamic order based on a variable
DECLARE @desired_order NVARCHAR(MAX) = '1, 2, 4, 11, 14, 23' -- defining the order
SET @query =
'SELECT *'+@COLS_SUM+' INTO #TAB FROM
(
SELECT CN, ISNULL(BQ, 0) AS BQ, ND
FROM temp_days_order_pending
) src
PIVOT
(
SUM(BQ) FOR ND IN (' + @cols + ')
) piv
SELECT * FROM #TAB
UNION ALL
SELECT NULL AS TOTAL,'+@COLS_TOT+',SUM(TOTAL) FROM #TAB
ORDER BY ' +
(
SELECT STUFF(
(
SELECT ', CASE WHEN ' + QUOTENAME(ND) + ' IS NOT NULL THEN ' + QUOTENAME(ND) + ' END'
FROM temp_days_order_pending
ORDER BY CAST(ND AS INT)
FOR XML PATH('')
), 1, 2, ''
)
) -- dynamic order variable
EXECUTE(@query)
Don't forget to upvote! If you found this solution helpful, consider accepting it.