使用动态数据透视时的总计(SUM)行

Total (SUM) Row whilst using dynamic Pivot

我正在尝试在使用动态数据透视表时对每一行进行总计(SUM)。如图所示。

我已经设法获得了每个字段(站点)的 SUM,我现在需要的是一列总计(SUMS)每一行(可以包含多个站点)。 (如果可能的话,通过扩展我当前的 tsql)

这是我的工作重点。 drawpersite 是一个包含字段

的视图
Name(varchar(50)),Site(varchar(50)), Draw(decimal(19, 4),Trade(varchar(50))

我已将其放入视图中以隐藏获取数据所需的所有连接。 下面的查询大部分拼凑在一起,但按预期工作(除了所有站点的总数(行总数)

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT
  @columns += N', p.' + QUOTENAME([SiteName])
FROM (SELECT
    [Site] AS [SiteName]
  FROM [dbo].[drawpersite] AS p
  GROUP BY [Site]) AS x;
SET @sql = N'
SELECT [Name],[Trade], ' + STUFF(@columns, 1, 2, '') + ' FROM (
SELECT [Name],[Trade], [Draw] AS [Quantity], [Site] as [SiteName] 
    FROM [dbo].[drawpersite]) AS j PIVOT (SUM(Quantity) FOR [SiteName] in 
       (' + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '') + ')) AS p;';
EXEC sp_executesql @sql

我已经看到其他关于此的问题,但我仍在努力解决它。

编辑

这是来自视图 DrawPerSite 的数据,这是一个没有分组的平面列表。它将每个站点的每个 Draw 显示为新记录,如日志。所以每个用户(姓名)可以有多个条目,甚至每个站点多个条目。

我正在接受这个并且需要显示每个名称,例如管理员每个站点的总抽奖(金额)。

因此,根据上面的数据,通过我当前的数据透视查询,我得到了这个结果集。这是我需要每行总数的结果集。

EDIT2

显示第二条记录未合计的屏幕截图。

我只想将这些站点添加到下一级:

DECLARE
    @columns NVARCHAR(MAX)
    , @columns_outer NVARCHAR(MAX)
    , @sums NVARCHAR(MAX)
    , @sql NVARCHAR(MAX);

SET @columns = N'';
SET @columns_outer = N'';
SET @sums = N'';

SELECT @columns += N', p.' + QUOTENAME([SiteName])
FROM
    (
        SELECT [Site] AS [SiteName]
        FROM [dbo].[drawpersite] AS p
        GROUP BY [Site]
    ) AS x;

SELECT @columns_outer += N', p2.' + QUOTENAME([SiteName])
FROM
    (
        SELECT [Site] AS [SiteName]
        FROM [dbo].[drawpersite] AS p
        GROUP BY [Site]
    ) AS x;

SELECT @sums += N' + ISNULL(' + QUOTENAME([SiteName]) + ', 0)'
FROM
    (
        SELECT [Site] AS [SiteName]
        FROM [dbo].[drawpersite] AS p
        GROUP BY [Site]
    ) AS x;

SET @sql = N'
    SELECT [Name], [Trade], ' + STUFF(@columns_outer, 1, 2, '') + ', ' + STUFF(@sums, 1, 3, '') + ' [Total] FROM (
    SELECT [Name], [Trade], ' + STUFF(@columns, 1, 2, '') + ' FROM (
    SELECT [Name],[Trade], [Draw] AS [Quantity], [Site] as [SiteName] 
    FROM [dbo].[drawpersite]) AS j PIVOT (SUM(Quantity) FOR [SiteName] in 
    (' + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '') + ')) AS p) AS p2;';

EXEC sp_executesql @sql