存储过程,以基于逗号分隔的值来透视列

时间:2019-03-06 11:52:40

标签: sql sql-server tsql stored-procedures

我尝试运行下面的代码来将由逗号分隔的ProvisionedDirectAddress列值的值拆分为一个新列。但是,它似乎不起作用

DECLARE  @SQLQuery AS NVARCHAR(MAX)
    DECLARE  @PivotColumns AS NVARCHAR(MAX)

    SELECT   @PivotColumns= COALESCE(@PivotColumns + ',','') + QUOTENAME(ProvisionedDirectAddress)
    FROM (SELECT distinct ProvisionedDirectAddress from SearchTable) AS PivotExample


     SET @SQLQuery=N'
    SELECT A.Name,T.* FROM
    (
    select  NPI,MAX(firstname)FirstName from SearchTable
    GROUP BY NPI
    ) a

    inner join 
    (
    select NPI, '+@PivotColumns+' from
    (
    SELECT
           NPI,MAX(firstname)FirstName,MAX(LastName)LastName,
         STUFF(
             (SELECT   "," + ProvisionedDirectAddress
              FROM SearchTable
              FOR XML PATH (''))
              , 1, 1, '')  AS ProvisionedDirectAddress
    FROM SearchTable  GROUP BY  NPI
    ) B

    Pivot(
    Min (ProvisionedDirectAddress) for ProvisionedDirectAddress  in('+@PivotColumns+')
    )
    as Pivottable
    ) t on t.NPI=A.NPI'

    EXEC sp_executesql @SQLQuery

enter image description here

  

我需要用逗号分隔的Provisioneddirectaddress列值   出现为新列

0 个答案:

没有答案