列到逗号分隔列[重复]

时间:2022-07-03 00:19:03

This question already has an answer here:

这个问题在这里已有答案:

--Editing this as my question was marked as a duplicate. I'm having an issue implementing STUFF and the "trick" FOR XML PATH when my query contains a join.

- 编辑此项,因为我的问题被标记为重复。当我的查询包含连接时,我遇到了实现STUFF和“技巧”FOR XML PATH的问题。

I have a single column that I have been trying to convert to a single column and single row. The data structure returned from the query below is:

我有一个列,我一直试图转换为单列和单行。从以下查询返回的数据结构是:

col1
1 
2
3

I'd like it to be comma delimited like so: col1 1,2,3

我希望它像这样用逗号分隔:col1 1,2,3

The query I have is as follows:

我的查询如下:

select 
  u_id
from 
  tabl1 tb
  inner join CTEE f on f.aid = tb.a_id
group by 
  u_id

I tried to incorporate STUFF and a FOR XML PATH in this query but keep failing to do so. Can anyone point me in the right direction. I've done this for multiple columns when concatenating rows into a comma delimited column, but for some reason this is driving me crazy.

我试图在此查询中包含STUFF和FOR XML PATH,但仍然没有这样做。任何人都可以指出我正确的方向。在将行连接到逗号分隔列时,我已经为多个列完成了此操作,但由于某种原因,这让我发疯。

1 个解决方案

#1


0  

Try this:

尝试这个:

    create table #tt
    (id int)

    insert into #TT values (1)
    insert into #TT values (2)
    insert into #TT values (3)

    Select stuff((select ',' + convert(Varchar(1), id)
    from #tt
    Order By 1 For XML Path('')),1,1,'')

#1


0  

Try this:

尝试这个:

    create table #tt
    (id int)

    insert into #TT values (1)
    insert into #TT values (2)
    insert into #TT values (3)

    Select stuff((select ',' + convert(Varchar(1), id)
    from #tt
    Order By 1 For XML Path('')),1,1,'')