2017-12-16 13 views
0

2列、[Owner Name]Addressデータと私のテーブルOwnerです:私は、出力の下に必要N行以下のSQL Server 2008 R2の列にデータ

Owner Name  Address 
----------------------- 
CURRENT OWNER AD1 
CURRENT OWNER AD2 
CURRENT OWNER AD3 
CURRENT OWNER AD4 

Owner Name Address1 Address2 Address3 Address4 
---------------------------------------------------------- 
CURRENT OWNER AD1  AD2   AD3   AD4 

アドレスは複数とすることができます所有者名に対して1000より大きい

答えて

1
あなたは、動的SQLを使用することができます

PIVOTはこれを行うには:

DECLARE 
    @MaxAddresses int = (SELECT MAX(C) FROM (SELECT COUNT([Owner Name]) C FROM [Owner] GROUP BY [Owner Name]) Q) 
    , @AddressHeaders varchar(max) = '' 
    , @n int = 1 

WHILE @n <= @MaxAddresses 
BEGIN 

    SET @AddressHeaders = @AddressHeaders + ', Address' + CAST(@n as varchar) 

    SET @n = @n + 1 

END 

SET @AddressHeaders = STUFF(@AddressHeaders, 1, 2, '') 

DECLARE @SQL varchar(max) = 
    ' 
     SELECT [Owner Name], ' + @AddressHeaders + ' 
     FROM 
      (
       SELECT 
        [Owner Name] 
        , [Address] 
        , ''Address'' + CAST(ROW_NUMBER() OVER (PARTITION BY [Owner Name] ORDER BY [Address]) AS varchar) AddressHeader 
       FROM [Owner] 
      ) Q 
      PIVOT 
      (
       MAX([Address]) 
       FOR AddressHeader IN (' + @AddressHeaders + ') 
      ) P 
    ' 

EXEC (@SQL) 
関連する問題