title: re - arrange table
body: <p>I have a table like this:</p>
  
  <pre><code>ID    Country       InternetTLD       CallingCode
  1     Nicaragua      .ni                +505
  2     USA            .us                +1
  3     Spain          .es                +34
  4     Germany        .de                +49
  </code></pre>
  
  <p>and I need a result like this</p>
  
  <pre><code>  1           2         3         4
  Nicaragua     USA      Spain     Germany
    .ni         .us       .es        .de
   +505          +1        +34       +49
  </code></pre>
  
  <p>I have tried with pivot but I just get to convert one column row, but in this case for every row in the first table it should be a column in the resulting table.</p>
  
  <p>this is my code:</p>
  
  <pre><code>Create table #SampleTable (
  ID int,
  Country nvarchar(50),
  InternetTLD nvarchar(50),
  CallingCode nvarchar(50)
  );
  
  insert into #SampleTable (ID, Country, InternetTLD, CallingCode)
  values
  (1, 'Nicaragua', '.ni', '+505'),
  (2, 'USA', '.us', '+505'),
  (3, 'Spain', '.es', '+34'),
  (4, 'Germany', '.de', '+49')
  
  
  
  
  DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
  DECLARE @ColumnName AS NVARCHAR(MAX)
  declare @PivotSelectColumnNames AS NVARCHAR(MAX)
  
  --Get distinct values of the PIVOT Column 
  SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
         + QUOTENAME(ID)
  FROM (SELECT ID FROM #SampleTable ) AS ID
  
  --Get distinct values of the PIVOT Column with isnull
  SELECT @PivotSelectColumnNames 
      = ISNULL(@PivotSelectColumnNames + ',','')
      + 'ISNULL(' + QUOTENAME(ID) + ', 0) AS '
      + QUOTENAME(ID)
  FROM (SELECT ID FROM #SampleTable ) AS ID
  
  --Prepare the PIVOT query using the dynamic 
  SET @DynamicPivotQuery = 
    N'SELECT  ' + @PivotSelectColumnNames + '
      FROM #SampleTable 
      PIVOT(MAX(Country) 
            FOR ID IN (' + @ColumnName + ')) AS PVTTable '
  
  --Execute the Dynamic Pivot Query
  EXEC sp_executesql @DynamicPivotQuery
  
  DROP TABLE #SampleTable
  </code></pre>