如何在 SQL Server 2005 中以逗号分隔的单行显示多行值?
问题描述:
下面我展示了两个表格和结果表格.
Below I have shown two tables and also the result table.
如何以上面显示的方式获取结果表?
How can I get the result table in this manner as I shown on above?
答
select min(ID) as ID,
Val,
stuff((select ','+Cat
from Table2 as T2
where T1.Val = T2.Val
for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') as Cat
from Table2 as T1
group by Val
order by ID