I am creating a report for a client and which requires me to produce a Pivot query that uses a dynamic set of columns headers. I have achieved this, however I am struggling to introduce a working Grand total at the end. I know how to do this if the values are fixed but not using a dynamic set of column headers. Any help would be greatly appreciated :)
-- Construct the dynamic PIVOT query
DECLARE @cols AS NVARCHAR(MAX)
-- Get the distinct rates
SELECT @cols = COALESCE(@cols + ', ', '') + QUOTENAME(rate)
FROM (SELECT DISTINCT rate FROM #PayDetailNAme pay JOIN #DutyInfo2 duty ON pay.DUTY_ID = duty.Dutyid ) AS rate;
DECLARE @query AS NVARCHAR(MAX)
-- Construct the dynamic PIVOT query
SET @query = '
SELECT
[start],
[end],
EMPLOYEE,
pin,
' + @cols + '
FROM
(
SELECT
''' + @start + ''' as [Start],
''' + @end + ''' as [End],
EMPLOYEE,
pin,
Rate,
isnull(hours,0) as hours
from #PayDetailNAme pay
JOIN #DutyInfo2 duty
ON pay.DUTY_ID = duty.Dutyid
)
AS SourceTable
PIVOT
(
SUM(hours)
FOR rate IN (' + @cols + ')
)
AS PivotTable
WHERE COALESCE(' + @cols + ') IS NOT NULL
;';
I have looked at some online examples but could not get this to behave as expected
1条答案
按热度按时间ffdz8vbo1#
As I mentioned in the comments, this is much easier with conditional aggregation rather than the restrictive
PIVOT
operator. For conditional aggregation, when you want a grand total column you just useSUM
without a condition:For a dynamic statement, that isn't any different, you just put the
SUM
after your dynamic conditional aggregates. Assuming SQL Server 2017+ (and you haveSTRING_AGG
as a result), and with made up sample data (as there is none in the question), this results in a query like so: