Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Friends, I need your help to sort out this issue.
I have a data in the format as
Name Value
John 100
John 1000
John 2000
Smith 100
Smith 300

I need to output as
John 100, 1000, 2000
Smith 100, 300

I can get this using case when but now the count can be n number.
So i need to dynamic solution.
Please guide.
Posted
Comments
syed shanu 24-Dec-14 1:50am    
You need to create this using Pivot .
Check my article
http://www.codeproject.com/Articles/818756/Basic-SQL-Queries-for-Beginners#13

 
Share this answer
 
Comments
King Fisher 24-Dec-14 2:17am    
Good Guidance :)
Maciej Los 24-Dec-14 2:24am    
Thank you, King ;)
Check this query hope this will help you.

SQL
--Create sample table
create table samplePivot(
Name varchar(50),
itemValue int
)

--Insert sample record
insert into samplePivot(Name,itemValue) values('John',100)
insert into samplePivot(Name,itemValue) values('John',1000)
insert into samplePivot(Name,itemValue) values('John',2000)
insert into samplePivot(Name,itemValue) values('Smith',100)
insert into samplePivot(Name,itemValue) values('Smith',300)

--Pivot query for your result

DECLARE @MyColumns AS NVARCHAR(MAX),
    @SQLquery  AS NVARCHAR(MAX)
-- here first we get all the ItemName which should be display in Columns we use this in our necxt pivot query
select @MyColumns = STUFF((SELECT ',' + QUOTENAME(itemValue) 
                    FROM samplePivot
                    GROUP BY itemValue
                    ORDER BY itemValue
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
        select @MyColumns
        
-- here we use the above all Item name to disoplay its price as column and row display
set @SQLquery = N'SELECT Name,' + @MyColumns + N' from 
             (
                 SELECT 
       Name, 
        itemValue  as itemValue
    FROM samplePivot
            ) x
            pivot 
            (
                 sum(itemValue)
                for itemValue in (' + @MyColumns + N')
            ) p '
exec sp_executesql @SQLquery;
 
Share this answer
 
Comments
Maciej Los 24-Dec-14 2:24am    
+5 for effort!
syed shanu 24-Dec-14 2:25am    
Thank You
Try this Dynamic Pivot :

http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/[^]

The Best way is try yourself :)
 
Share this answer
 
Comments
Maciej Los 24-Dec-14 2:24am    
Nice!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900