我有一个select输出,输出如下:
pid-------Name------------------response
147------Factory Influenced-----Fish Paste
147------Factory Influenced-----Contract Packer
147------Factory Influenced-----Cereals
147------Factory Influenced-----Biscuits
154------Factory Influenced-----Werda
154------Factory Influenced-----Worcester
158------Factory Influenced-----Moirs
158------Factory Influenced-----Oats
158------Factory Influenced-----Noogy
157------Factory Influenced-----Safari Nuts
158------Factory Influenced-----Savoury Foods
我想做的是让“工厂影响”成为一个专栏,并将“响应”作为字段。但是,我想将这些值连接如下:
pid-----Factory Influenced
147-----Fish Paste, Contract Packer, Cereals, Biscuits
154-----Werda, Worcester
158-----Moirs, Oats, Noogy, Safari Nuts, Savoury Foods
任何有关此方面的帮助都将受到高度赞赏。
答案 0 :(得分:4)
将多行连接到单个列的过程不是PIVOT,PIVOT是将数据行转换为列时的过程。由于您要创建以逗号分隔的值列表,因此代码不同。
您可以使用FOR XML PATH
和STUFF
创建列表:
select t1.pid,
t1.name,
STUFF(
(SELECT ', ' + t2.response
FROM yourtable t2
where t1.pid = t2.pid
FOR XML PATH (''))
, 1, 1, '') AS response
from yourtable t1
group by t1.pid, t1.name;
或者您可以CROSS APPLY
使用FOR XML PATH
:
select DISTINCT t1.pid,
t1.name,
response = left(t2.response, len(t2.response)-1)
from yourtable t1
cross apply
(
select t2.response + ', '
from yourtable t2
where t1.pid = t2.pid
FOR XML PATH('')
) t2 (response);
见SQL Fiddle with Demo。两个版本都会得到以下结果:
| PID | NAME | RESPONSE |
|-----|--------------------|------------------------------------------------|
| 147 | Factory Influenced | Fish Paste, Contract Packer, Cereals, Biscuits |
| 154 | Factory Influenced | Werda, Worcester |
| 157 | Factory Influenced | Safari Nuts |
| 158 | Factory Influenced | Moirs, Oats, Noogy, Savoury Foods |