在 SQL Server 中将多行合并为一个逗号分隔值的列
问题:
您需要将具有公共标识符的多行合并到单个列中,其中值以逗号分隔。例如,您希望将数据从:
<code>[TicketID] [Person] T0001 Alice T0001 Bob T0002 Catherine T0002 Doug T0003 Elaine</code>
转换为:
<code>[TicketID] [People] T0001 Alice, Bob T0002 Catherine, Doug T0003 Elaine</code>
SQL Server 2005 的解决方案:
<code class="language-sql">STUFF(ISNULL((SELECT ', ' + x.Person FROM @Tickets x WHERE x.TicketID = t.TicketID GROUP BY x.Person FOR XML PATH (''), TYPE).value('.','VARCHAR(max)'), ''), 1, 2, '')</code>
示例查询:
<code class="language-sql">SELECT t.TicketID, STUFF(ISNULL((SELECT ', ' + x.Person FROM @Tickets x WHERE x.TicketID = t.TicketID GROUP BY x.Person FOR XML PATH (''), TYPE).value('.','VARCHAR(max)'), ''), 1, 2, '') [无前导逗号], ISNULL((SELECT ', ' + x.Person FROM @Tickets x WHERE x.TicketID = t.TicketID GROUP BY x.Person FOR XML PATH (''), TYPE).value('.','VARCHAR(max)'), '') [如果非空则有前导逗号] FROM @Tickets t GROUP BY t.TicketID</code>
以上是如何将多个 SQL Server 行合并为单个逗号分隔列?的详细内容。更多信息请关注PHP中文网其他相关文章!