Click here to Skip to main content
15,897,032 members
Please Sign up or sign in to vote.
4.00/5 (4 votes)
Hi guys/girls

I am having a problem with SQL. Its kinda hard to explain but going to try

I have a query returning results as shown in the example:

name,surname,telno,result
john,joe,011,45
john,joe,011,55
john,joe,011,50
piet,pee,011,30
piet,pee,011,44
piet,pee,011,45
piet,pee,011,45


and I want to get the results like so

john,joe,011,45,55,50
piet,pee,011,40,44,45,45


The problem I am having is that the number of result per person is not always the same number, example john has 3 results , and piet has 4 results and so on.

Please note that the "," is for a new column

Can anyone assist with this please ?
Posted
Updated 29-May-11 23:20pm
v3
Comments
That's Aragon 30-May-11 5:15am    
Edited for grammar and better readability.
Unforgiv3n 30-May-11 5:19am    
thanks

The best I think you can do is return the results as an xml string, something like this

SQL
SELECT        name, surname, STUFF
                             ((SELECT        ',' + result AS Result
                                 FROM            results AS t1
                                 WHERE        (t2.name = name) FOR XML path('')), 1, 1, '') AS Results
FROM            results AS t2
GROUP BY name, surname
ORDER BY name
.

I tested this on a table called results, so substitute your own table name.

Hope this helps
 
Share this answer
 
v2
Comments
arindamrudra 30-May-11 7:25am    
Great work. I was also trying this one with XML. But could not make it. Thanks a lot. I also tested it and it is working fine. Great work.... My +5
Wayne Gaylard 30-May-11 7:30am    
My Pleasure
AFAIK, you can't do it with variable number of columns: all the returns have the same, fixed column count.
You could return a DBNULL for empty columns though, in which case it is very similar to the MSDN example[^]
 
Share this answer
 
Comments
Unforgiv3n 30-May-11 5:38am    
not realy wat im looking for, because the case statement wil be to big, because the column contains about 10000 different values
You can write a code to select your table values in pivot concept.
In Sql server we can write a query to convert a row to column.
you can write a pivot table query.
 
Share this answer
 
Comments
Unforgiv3n 30-May-11 5:37am    
is it possible for a example ? and will it work on a column with varchar
[no name] 31-May-11 6:01am    
Yes,
It works with every data type present in your SQL Server.
follow the links this will help you.

1. http://www.mssqltips.com/tip.asp?tip=1019
2. http://www.sqlprof.com/blogs/sqldev/archive/2008/04/12/pivots-with-dynamic-columns-in-sql-server-2005-2008.aspx


marks this as answer this will help others to find the solutions.
happy coding!

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