Click here to Skip to main content
16,016,168 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a query with the following result:
query:
SQL
SELECT Tasks.TaskId, Comments.Comment, comments.timespent       
          FROM   comments
          INNER JOIN tasks ON comments.entityid = tasks.taskid                
          WHERE  ( comments.entity = 1 ) 
          GROUP  BY Tasks.TaskId, Comments.Comment, comments.timespent

result:

TaskID Comment TimeSpent
_______ ________ _________
111754 C1 4
111754 C2 1
111754 C3 79

Please tell me how should I write my query to get the result as follows:

TaskID Comment TimeSpent
_______ ___________ _________
111754 ,C1,C2,C3 84

Thanks in advance.
Posted

You need to use one of the SQL Server string concatenation tricks, as described here. I personally prefer FOR XML PATH
SQL
SELECT Tasks.TaskId, SUM(comments.timespent),
stuff( (SELECT ','+Comment
               FROM comments p2
               WHERE p2.entityid = comments.entityid
               ORDER BY Comment
               FOR XML PATH(''), TYPE).value('.', 'varchar(max)')
            ,1,1,'')
       AS Comments
          FROM   comments
          INNER JOIN tasks ON comments.entityid = tasks.taskid                
          WHERE  ( comments.entity = 1 ) 
          GROUP  BY Tasks.TaskId
 
Share this answer
 
Try PIVOT[^].
 
Share this answer
 
Comments
chaau 27-Jan-14 23:09pm    
I think PIVOT will not do what the OP asks. Do you want to review your 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