开发者

Subquery returning csv written values in a Main Query Column, possible?

开发者 https://www.devze.com 2023-04-05 23:20 出处:网络
I got to tables. TABLE 1: [..fields..] [CATEGORIE] [..fields..开发者_开发问答] TABLE 2: [..fields..] [ID] [CATEGORIE] [..fields..]

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


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:

  • SQL Query to get aggregated result in comma seperators along with group by column in SQL Server
  • SQL same unit between two tables needs order numbers in 1 cell
0

精彩评论

暂无评论...
验证码 换一张
取 消