Click here to Skip to main content
15,904,155 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a sql table that look like:

SQL Query:

Select * from Fee

Output look like :-

StudentID - Month
101 - 3
101 - 4
101 - 5
102 - 1
102 - 2

but i need output like:-

StudentID - Month
101 - 3,4,5
102 - 1,2


how can i do it using sql query.

What I have tried:

SQL
DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' ,'') + Convert(nvarchar(8),Month)  from fees where studentid in (101,102)
group by studentid,month
SELECT @listStr


i am trying this query but the output give this query like:

Month
3,4,5,1,2
Posted
Updated 22-Dec-16 1:07am

1 solution

Try:
SQL
SELECT StudentId, Months =
   STUFF((SELECT ', ' + CONVERT(NVARCHAR(2), [Month])
          FROM FEES f
		  WHERE f.StudentId = a.StudentID
   FOR XML PATH ('')), 1, 2, '')
FROM Fees a
GROUP BY StudentId
 
Share this answer
 
Comments
Maciej Los 23-Dec-16 1:57am    
5ed!

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