T SQL-多次Conconate列 [英] T SQL - Conconate Column Multiple Times

查看:72
本文介绍了T SQL-多次Conconate列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有下表:

ID | Product_Image
300 | /300-01.jpg
300 | /300-02.jpg
301 | /301.jpg
302 | /302.jpg

ID | Product_Image
300 | /300-01.jpg
300 | /300-02.jpg
301 | /301.jpg
302 | /302.jpg

每个ID可能有无限数量的图像.我需要将所有图像引用连接到一栏中,并且在生成以下输出时遇到问题:

There could be an unlimited number of images per ID. I need to concatenate all the image references into one column, and I am having trouble generating the following output:

ID | Product Images
300 | /300-01.jpg; /300-02.jpg;
301 | /301.jpg;

ID | Product Images
300 | /300-01.jpg; /300-02.jpg;
301 | /301.jpg;

推荐答案

-- cte with test data
;with T (ID, Product_Image) as
(
select 300, '/300-01.jpg' union all
select 300, '/300-02.jpg' union all
select 301, '/301.jpg' union all
select 302, '/302.jpg'
)

select
  T.ID,
  (select T2.Product_Image+'; '
   from T as T2 
   where T.ID = T2.ID
   for xml path(''), type).value('.[1]', 'nvarchar(max)') as Product_Images
from T
group by T.ID

结果:

ID   Product_Images
---- -------------------------
300  /300-01.jpg; /300-02.jpg; 
301  /301.jpg; 
302  /302.jpg; 

这篇关于T SQL-多次Conconate列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆