I need to concatenate two columns separately across multiple rows of data in SQL Server that are joined between two tables.
For instance, I have an "association" table and "market" table as shown below"
Association:
user_id | role_id | market_id
-------------------------------
1 | a | 1
1 | a | 2
2 | c | 3
2 | c | 4
2 | c | 5
Market:
market_id | market_name
-----------------------
1 | Arizona
2 | Utah
3 | Indiana
4 | Illinois
5 | Kentucky
I need to concatenate the market_id in the Association table into a single value, per user id, as well as bring in the concatenated market names from the Market table, with my desired output looking like:
user_id | role_id | market_ids | market_names
--------------------------------------------------
1 | a | 1,2 | Arizona,Utah
2 | c | 3,4,5 | Indiana,Illinois,Kentucky
Now, I am able to successfully concatenate the market id's but still end up with multiple rows of data for each market using the following SQL:
SELECT DISTINCT
a.user_id,
a.role_id,
SUBSTRING(
(
SELECT DISTINCT ', ' + market_id AS [text()]
FROM Association aa
WHERE a.user_id = aa.user_id
FOR XML PATH ('')
), 2, 1000) [market_ids],
SUBSTRING(
(
SELECT DISTINCT ', ' + market_name AS [text()]
FROM Market bb
WHERE a.market_id = bb.market_id
FOR XML PATH ('')
), 2, 1000) [Market Name]
FROM
Association a
INNER JOIN
Market b
ON a.market_id = d.market_id
Any ideas on how to achieve the second concatenation?