根据 ID 连接值
此问题旨在将每个 ID 具有多行和单个“标签”列的表转换为每个 ID 一行和一个串联的“标签”列的表。每个标签应以逗号分隔。
提供的数据由以下观察组成:
Response_ID | Label |
---|---|
12147 | It was not clear |
12458 | Did not Undersstand |
12458 | Was not resolved |
12458 | Did not communicate |
12586 | Spoke too fast |
12587 | Too slow |
所需的输出是:
Response_ID | Label |
---|---|
12147 | It was not clear |
12458 | Did not Undersstand,Was not resolved,Did not communicate |
12586 | Spoke too fast |
12587 | Too Slow |
实现此转换,可以使用以下代码片段:
declare @T table(Response_ID int, Label varchar(50)) insert into @T values (12147, 'It was not clear'), (12458, 'Did not Undersstand'), (12458, 'Was not resolved'), (12458, 'Did not communicate'), (12586, 'Spoke too fast'), (12587, 'Too slow') select T1.Response_ID, stuff((select ','+T2.Label from @T as T2 where T1.Response_ID = T2.Response_ID for xml path(''), type).value('.', 'varchar(max)'), 1, 1, '') as Label from @T as T1 group by T1.Response_ID
'stuff'函数中的子查询使用串联通过''操作符和XML方法来处理标签的组合。 'type' 参数的 'value' 函数将 XML 输出转换为 varchar(max) 类型,以确保串联结果的正确显示。
请注意,如果子查询中没有 order by 语句,则串联结果的顺序无法保证字符串。
以上是如何根据 ID 将多个标签连接成一行?的详细内容。更多信息请关注PHP中文网其他相关文章!