多个数据透视表

时间:2014-08-06 07:03:09

标签: sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2 sql-server-2012

我们有一张如下表格 。 。 。 。

 ID WOID    InfoCode    PersonID    PersonSource    FieldID FieldName       FieldValue
 --------------------------------------------------------------------------------------  
 1  2     AGMDDFR         7          CSS2C            1       Email           sg
 2  2     AGMDDFR         7          CSS2C            2       Phone           245345
 3  2     AGMDDFR         7          CSS2C            3       FAX             345345
 4  2     AGMDDFR         7          CSS2C            4       ArticleNumber  345
 5  2     AGMDDFR         7          CSS2C            6       Description     etete
 6  2        ABC          7          CSS2C            12      Enter Email     
 7  2     AGMDDFR         8          CSS2C             1      Email           tet@gmi.com
 8  2     AGMDDFR         8          CSS2C             2      Phone           9988776655
 9  2     AGMDDFR         8          CSS2C             3      FAX             898383838
 10 2     AGMDDFR         8          CSS2C             4      Article Number  777777
 11 2     AGMDDFR         8          CSS2C             6      Description     asdff    

我们希望基于“信息代码”的输出如下所示,我们需要提取如下表格。

---1stTable(AGMDDFR)----    
WOID   PersonID  PersonSource   Email        Phone       Fax      ArticleNumber  Description
 -----------------------------------------------------------------------------------------  
 2     7            CSS2C       sg          245345      345345     345            etete         
 2     8            CSS2C      tet@gmi.com  9988776655  898383838  777777         asdff


--2ndTable(ABC)

WOID   PersonID  PersonSource  Enter Email
 2     7            CSS2C         ssss

请帮我解决这个问题..

1 个答案:

答案 0 :(得分:1)

由于您需要为每个InfoCode值返回不同的列,因此您需要查看使用动态SQL来获取结果。这将创建一个SQL字符串,其中包含每个参数的列列表。然后,您将执行SQL字符串以获得最终结果。

基本语法为:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),
  @InfoCode varchar(10)

DECLARE @ParmDefinition NVARCHAR(500)

set @InfoCode = 'AGMDDFR'
SET @ParmDefinition = '@InfoCode varchar(10)'

select @cols = STUFF((SELECT ',' + QUOTENAME(FieldName) 
                    from yourtable
                    where InfoCode = @InfoCode
                    group by FieldName, FieldID
                    order by FieldId
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT WOID, PersonID, PersonSource, ' + @cols + ' 
            from 
            (
              select WOID, PersonID, PersonSource, 
                FieldName, FieldValue
              from yourtable
              where InfoCode = @InfoCode
            ) x
            pivot 
            (
                max(FieldValue)
                for FieldName in (' + @cols + ')
            ) p '

EXEC sp_executesql @query, @ParmDefinition, @InfoCode = @InfoCode;

请参阅SQL Fiddle with Demo