Subquery returning csv written values in a Main Query Column, possible?
-
23-01-2021 - |
Question
I got to tables.
TABLE 1: [..fields..] [CATEGORIE] [..fields..]
TABLE 2: [..fields..] [ID] [CATEGORIE] [..fields..]
I want to connect a bit special and tried it like this:
SELECT [..other fields..], CATEGORIE, (SELECT ID FROM TABLE2 WHERE TABLE2.CATEGORIE = TABLE1.CATEGORIE) FROM TABLE1;
I want to have the IDs of the SubQuery in on Column of the Main Query
like that ( [] are representing columns)
[resultfield1] [resultfield2] [resultfield3] [ID1,ID2,ID3,ID4,...]
is there a way to afford it?
Help is very appreciated,
thanks in advance
Solution
As hard as it is to read understand your question, what you want is to use FOR XML PATH
:
select
categorie,
stuff((select ', ' + id
from table2 t2 where t1.categorie = t2.categorie
for xml path('')),
1,2,'') [IDs]
from table1 t1
Further reading here:
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow