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