最后添加总列,用于动态透视SQL Server查询

时间:2017-10-10 13:53:06

标签: sql-server totals dynamic-pivot

我可以设法在SQL Server中进行动态数据透视查询,如下所示:

DECLARE @sql nvarchar(max),
        @columns nvarchar(max) 

SELECT @columns = STUFF((SELECT DISTINCT ',' + QUOTENAME(nationality) 
                         FROM NewComers  
                         FOR XML PATH('')), 1, 1, '')

SELECT @sql = 'SELECT p.registrationdate, '+ @columns +
              ' FROM (SELECT s.registrationdate, s.Nationality FROM newcomers s) AS t
                PIVOT (
                    COUNT(Nationality) FOR nationality IN (' + @columns+ ')) p'

EXEC (@sql)

我的问题是我想在结果的末尾添加一列。所以目前我得到了这个结果:

  registrationdate   GER   TUR   CAN   AUS  
 ------------------ ----- ----- ----- ----- 
  16/11/2016          10     8     6     7  
  21/08/2020           4     5     3     2  
  08/04/2019           1     3     5     0  

我需要这样做:

  registrationdate   GER   TUR   CAN   AUS   Total  
 ------------------ ----- ----- ----- ----- ------- 
  16/11/2016          10     8     6     7      31  
  21/08/2020           4     5     3     2      14  
  08/04/2019           1     3     5     0       9  

我在Stack Overflow中尝试了几个解决方案,但我没有做任何事情。

非常感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

您可以将Total作为联合行添加到newcomer表中,然后手动将“Total”字符串添加到@columns变量中吗?

基本上创建一个新成员表的CTE,其中一个工会按照您的日期进行分组,并将总数加起来并将“总计”一词粘贴到国籍栏中。

然后只需将Total添加到@columns字符串中即可将其转出。

这样的东西?我目前无法访问SQL Server来测试它。

DECLARE @sql nvarchar(max),
        @columns nvarchar(max) 

SELECT @columns = STUFF((SELECT DISTINCT ',' + QUOTENAME(nationality) 
                         FROM NewComers  
                         FOR XML PATH('')), 1, 1, '')

SELECT @sql = '

;with CTE as (
 select registrationdate, Nationality, count(Nationality) as Cnt from newcomers group by registrationdate, Nationality
 union all
 select registrationdate, ''Total'', count(Nationality) as Cnt from newcomers group by registrationdate 
)

SELECT p.registrationdate, '+ @columns + ', Total' +
              ' FROM (SELECT registrationdate, Nationality, Cnt FROM CTE) AS t
                PIVOT (
                    max(Cnt) FOR nationality IN (' + @columns+ ',Total)) p'

EXEC (@sql)