0

I need to convert a column data into single row with multiple columns

Example - I created a temp table to load data for the column

CREATE TABLE TestC (Comments Char(100), Row_Count [int] IDENTITY(1,1))

INSERT INTO TestC VALUES('A'),('B'),('C'),('D')

Select Min( Case When Row_Count = 1 Then Comments End ) As Comments 
, Min( Case When Row_Count = 2 Then Comments End ) As Comments 
, Min( Case When Row_Count = 3 Then Comments End ) As Comments 
, Min( Case When Row_Count = 4 Then Comments End ) As Comments 
, Min( Case When Row_Count = 5 Then Comments End ) As Comments 
, Min( Case When Row_Count = 6 Then Comments End ) AS Comments 
, Min( Case When Row_Count = 7 Then Comments End ) AS Comments 
FROM TestC 

Result

I am trying to make it dynamic query, Below is the code snippet I am trying out currently

DECLARE @sql AS NVARCHAR (MAX);
SELECT   @sql =  ' SELECT Min (CASE WHEN [Row_Count] =' + CAST ([Row_Count] AS CHAR(5)) + 
' THEN [Comments] END) AS Comments'
FROM     [dbo].[TestC];
SET @sql = @sql + N' FROM  [dbo].[TestC] ';
PRINT @sql
EXECUTE sp_executesql @sql;

This still needs some tweaking. Appreciate your Help..

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Siva
  • 2,791
  • 5
  • 29
  • 33

1 Answers1

1

You can use pivot query such as below :

SELECT Pvt.*
FROM (
    SELECT *
    FROM TestC
    )AS P
PIVOT (MIN(Comments) FOR Row_Count IN ([1],[2],[3],[4],[5],[6],[7]))Pvt

EDIT : You can see below links:

Dynamic Pivot Link 1

Dynamic Pivot Link 2

Dynamic Pivot Link 3

Community
  • 1
  • 1
mehdi lotfi
  • 11,194
  • 18
  • 82
  • 128