使用动态Pivot时的总(SUM)行

时间:2017-12-30 23:07:47

标签: sql sql-server tsql pivot dynamic-pivot

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

Total for row

我已经设法为每个字段(站点)获取SUM,我现在需要的是一个列Totals(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显示为新记录,如日志。因此,每个用户(名称)可以有多个条目,甚至每个站点有多个条目。

enter image description here

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

从上面的数据来看,使用我当前的数据透视查询,我得到了这个结果集。这是我需要每行总计的结果集。

enter image description here

EDIT2

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

enter image description here

1 个答案:

答案 0 :(得分:1)

我只想在下一级添加网站:

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