Sorry if this is covered elsewhere in another question, but I can't find any examples which exactly match what I need and I'm getting confused.
I have data in the table like this :-
Name | Value
---------------
John | Dog
John | Cat
John | Fish
Bob | Python
Bob | Camel
And I would like the data like this....
Name | Value_1 | Value_2 | Value_3
-------------------------------------
John | Dog | Cat | Fish
Bob | Python | Camel | NULL
I don't want to use case statements because the dog, cat, fish etc there are 20+ possible values and they could change overtime.
Anyone got any pointers?
This comes close to what you're after. i've also included a table creation script and sample data for others to use. Inspiration for this solution came from here
-- Dynamic PIVOT
DECLARE @T AS TABLE(y INT NOT NULL PRIMARY KEY);
DECLARE
@cols AS NVARCHAR(MAX),
@y AS INT,
@sql AS NVARCHAR(MAX);
-- Construct the column list for the IN clause
-- e.g., [Dog],[Python]
SET @cols = STUFF(
(SELECT N',' + QUOTENAME(y) AS [text()]
FROM (SELECT DISTINCT [Value] AS y FROM dbo.table_1) AS Y
ORDER BY y
FOR XML PATH('')),
1, 1, N'');
-- Construct the full T-SQL statement
-- and execute dynamically
SET @sql = N'SELECT *
FROM (SELECT *
FROM dbo.table_1) AS D
PIVOT(MIN(value) FOR value IN(' + @cols + N')) AS P;';
PRINT @sql
EXEC sp_executesql @sql;
GO
Table creation:
CREATE TABLE [dbo].[Table_1](
[Name] [varchar](50) COLLATE Latin1_General_CI_AS NULL,
[Value] [varchar](50) COLLATE Latin1_General_CI_AS NULL
) ON [PRIMARY]
GO
Sample data:
insert into dbo.table_1 values ('John','Dog')
insert into dbo.table_1 values ('John','Cat')
insert into dbo.table_1 values ('John','Fish')
insert into dbo.table_1 values ('Bob ','Python')
insert into dbo.table_1 values ('Bob ','Camel')
This question is somewhat similar:
Cross Tab - Storing different dates (Meeting1, Meeting2, Meeting 3 etc) in the same column
Take a look at this :
http://dotnetgalactics.wordpress.com/2009/10/23/using-sql-server-20052008-pivot-on-unknown-number-of-columns-dynamic-pivot/
Might be helpful ..