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..

2
  • If i get it right you want to convert rows into columns, then why not simply crosstab it..!! Commented Jun 9, 2012 at 10:00
  • Yes. You just need to convert from rows to columns. Let me try cross tab Commented Jun 9, 2012 at 17:07

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This need to be dynamic actually.Here in the answer it is hardcoded

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.