SQL Server中的数据透视表,用于显示总值

时间:2015-04-22 06:32:19

标签: sql sql-server

我想使用数据透视表显示特定月份的费用。我已经为您的推荐应用了我的代码

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)

DECLARE @ColumnName AS NVARCHAR(MAX)

SELECT  @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(years) 
FROM (SELECT DISTINCT years FROM pivots) AS years

SET @DynamicPivotQuery =  N'SELECT  DISTINCT months, ' + @ColumnName + FROM pivots
      PIVOT(SUM(expense) FOR  years IN (' + @ColumnName + ')) AS PVTTable'

EXEC sp_executesql @DynamicPivotQuery

输出结果显示在

下方
    months  2014    2015    2016
    febuary 200 NULL    NULL
    january NULL    100 NULL
    january 500 NULL    NULL
    march   NULL    NULL    300

我想要的输出是1月值不应该重复两次。它应该更新null place.it不应该创建另一个值列

0 个答案:

没有答案