Lets say I have 2 tables:
1 with users
and another one which keeps record of which users used what codes.
Users ----- Id, Name 1, 'John' 2, 'Doe' Codes ------ Id, UserId, code 1, 1, 145 2, 1, 187 3, 2, 251
Now I want to pull a query that results he following
Name, UsedCodes 'John', '145,187' 'Doe', '251'
How can this be done with a query or stored procedure?
Since you haven’t specified the DB I’m giving you two options:MySql
With MySql you should simply use
GROUP_CONCAT()aggregate function.Microsoft SQL Server 2005+
Obviously the fastest way (no cursors, no coalesce…) of getting the same result on MS DB is by using
FOR XML PATH('')that simply omits XML elements.Other alternatives
Read this article, that explains all the possible ways of achieving this goal.