So, creating the data:
CREATE TABLE #t (id int, title nvarchar(5), tags nvarchar(3));
INSERT INTO #t (id,title,tags)
VALUES
(1,'P1583','2,5'),
(2,'P1234','1,3'),
(3,'P1456','1');
CREATE TABLE #tag (id int, title nvarchar(10));
INSERT INTO #tag (id,title)
VALUES
(1,'Pants'),
(2,'Shorts'),
(3,'Shirts'),
(4,'Tshirts'),
(5,'Skirts');
And using STRING_SPLIT and CROSS APPLY gives us:
SELECT #t.id, #t.title, #t.tags, tags.value, #tag.title
FROM #t
CROSS APPLY STRING_SPLIT(#t.tags,',') tags
INNER JOIN #tag ON tags.value = #tag.id;
id |
title |
tags |
value |
title |
1 |
P1583 |
2,5 |
2 |
Shorts |
1 |
P1583 |
2,5 |
5 |
Skirts |
2 |
P1234 |
1,3 |
1 |
Pants |
2 |
P1234 |
1,3 |
3 |
Shirts |
3 |
P1456 |
1 |
1 |
Pants |
From there you just STRING_AGG back together:
WITH exp
AS (
SELECT #t.id, #t.title, #t.tags, tags.value, #tag.title AS tag_title
FROM #t
CROSS APPLY STRING_SPLIT(#t.tags,',') tags
INNER JOIN #tag ON tags.value = #tag.id
)
SELECT id, title, STRING_AGG(tag_title,',') WITHIN GROUP (ORDER BY tag_title) AS tag_titles
FROM exp
GROUP BY id, title;