Hi
In below query how to display Grand Totals.
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(T2."U_A_M")
FROM Opch T0 inner join Pch1 T1 on T0."Docentry" = T1."DocEntry"
inner join Oitm T2 on T1."ItemCode" = T2."ItemCode"
where T2.U_A_M <> 'NA'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT itemcode, ' + @cols + ' from
(
SELECT T1."ItemCode",T1."LineTotal", T2."U_A_M"
FROM Opch T0 inner join Pch1 T1 on T0."Docentry" = T1."DocEntry"
inner join Oitm T2 on T1."ItemCode" = T2."ItemCode"
where T2.U_A_M <> ''NA''
) x
pivot
(
sum(linetotal)
for U_A_M in (' + @cols + ')
) p '
execute(@query)
I want to display total of all items.
itemcode Admin Purchase Sales GrandTotal
3000740003 NULL 61628.000000 NULL 61628.000000
3000820001 NULL NULL 141251.000000 141251.000000
3000740004 1000625.000000 NULL NULL 1000625.000000
3000810002 1306931.800000 NULL NULL 1306931.800000
2307557 61628 141251 2510436
Thanks
Loading
Muhammad Imran AnsariPosted Mar 6, 2025, 4:12 PM
Hello Ramco,
To display a Grand Total row at the bottom, you can use GROUPING SETS or a ROLLUP approach. However, since you are using Dynamic SQL with PIVOT, you need to modify the query to union the total row.
Good Luck!
Jignesh KumarPosted Mar 6, 2025, 3:59 AM
Hello Ramco,
You can add grand total using below query,
Daniel WrightPosted Mar 6, 2025, 12:46 AM
To display Grand Totals in your SQL query output, you can modify your existing query by adding a computation for the Grand Total. Here's how you can do it:
1. Add a computation in your SQL query that calculates the sum of each row to get the Grand Total.
2. Make sure you include this sum in your final query result set along with the individual columns.
Below is an example of how you can update your query to display the Grand Total:
By adding `ISNULL(SUM(' + @cols + '), 0) AS GrandTotal` to your SELECT statement inside the dynamic SQL query, you will get the Grand Total for each row in the result set. This way, you can see both the individual totals for Admin, Purchase, and Sales columns along with the Grand Total for each item.
I hope this helps you in displaying the Grand Totals effectively in your SQL query output. Let me know if you have any further questions or need additional clarification!