Click here to Skip to main content
16,016,168 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi All,

I have a query to make which i m finding difficult to make.

I have a table with following structure:

Id Field
1 'aaaa'
1 'bbbb'
2 'cccc'
2 'dddd'

I want the output from the query as follows:

1 'aaaa','bbbb'
2 'cccc','dddd'


SQL
CREATE TABLE #a
(
id INT ,
field varchar(1000)
)

INSERT INTO #a
        ( id, field )
VALUES  ( 1, -- id - int
          'aaaaa'  -- field - varchar(1000)
          )
          
INSERT INTO #a
        ( id, field )
VALUES  ( 1, -- id - int
          'bbbb'  -- field - varchar(1000)
          )
          
INSERT INTO #a
        ( id, field )
VALUES  ( 2, -- id - int
          'cccc'  -- field - varchar(1000)
          )
          
INSERT INTO #a
        ( id, field )
VALUES  ( 2, -- id - int
          'ffff'  -- field - varchar(1000)
          )



Please help me .....

Regards,
Gopal
Posted
Updated 8-Sep-11 2:15am
v3

 
Share this answer
 
I'm not a sql expert, but what you want to investigate the following t-sql commands:

COALESCE<br />
<br />
PIVOT


The PIVOT command will arrange the data the way you want it, and the COALESCE command will help you put the resulting dataset into a comma-delimited string.

Google is your friend.
 
Share this answer
 
Comments
[no name] 8-Sep-11 8:51am    
very bad very bad
#realJSOP 8-Sep-11 9:00am    
What does that mean? Why is it "very bad"? First, I preceded my statement with a disclaimer that I'm not a sql expert. Second, it may not have been the *best* answer, but certainly wasn't deserving of a 1-vote. I think you need to show a bit more respect.
Hi, gopalgupta

try this one.
SQL
SELECT id, (
           SELECT field+', '
           FROM  tableName WITH (NOLOCK)
           WHERE  a.id = id
           ORDER BY
                  field
                  FOR XML PATH('')
       ) AS field
FROM   tableName a WITH (NOLOCK)
GROUP BY
       id
 
Share this answer
 
v2
Comments
#realJSOP 8-Sep-11 9:14am    
Our DBA said using NOLOCK (or any hint for that matter) was generally bad practice. We don't have any instances of that hint in our sql code. Notice that I didn't 1-vote your answer, I merely commented on it.
Do you always have just two rows for each id? If that's true then you could try something like:
SQL
SELECT t1.Id,
       t1.Field,
       t2.Field
FROM   #a t1,
       #a t2
WHERE t1.Id = t2.Id
AND   t1.Field < t2.Field
 
Share this answer
 

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