动态列SQL数据透视表

时间:2016-10-19 12:46:31

标签: sql sql-server tsql pivot

我正在尝试使用动态标题在SQL中创建数据透视表。我的标题工作正常,但我无法弄清楚如何对行进行分组。

示例数据

CriteriaID     KSB_Requirement        ModuleID    Module_Title
   1         Understand something       5         Principles 1
   1         Understand something       6         Principles 2 
   1         Understand something       7         Principles 3 
   2         Learn something            5         Principles 1
   2         Learn something            6         Principles 2

我使用的结果:

DECLARE 
  @cols AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(Module_Title) 
            FROM Standards_Coverage_Pivot_Data
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT KSB_Requirement, ' + @cols + ' from 
            Standards_Coverage_Pivot_Data 
            pivot 
            (
                Count(CriteriaID)
                for Module_Title in (' + @cols + ')
            ) p '
 execute(@query);

...是

KSB_Requirement       Principle 1    Principle 2    Principle 3
Understand something      1              0              0
Understand something      0              1              0
Understand something      0              0              1
Learn something           1              0              0
Learn something           0              1              0

我真正想要展示的是:

KSB_Requirement       Principle 1    Principle 2    Principle 3
Understand something      1              1              1
Learn something           1              1              0

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

你几乎就在那里

DECLARE 
  @cols AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(Module_Title) 
            FROM Standards_Coverage_Pivot_Data
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT * from (Select KSB_Requirement,Module_Title,CriteriaID From Standards_Coverage_Pivot_Data) s
            pivot 
            (
                Count(CriteriaID)
                for Module_Title in (' + @cols + ')
            ) p '
 execute(@query);

返回

KSB_Requirement       Principles 1  Principles 2    Principles 3
Learn something       1             1               0
Understand something  1             1               1