【发布时间】:2020-09-23 19:26:53
【问题描述】:
我有一个复杂的查询返回:
MyID col1 col2 col3
1 A:11
1 A:21
1 A:31
1 C:13
1 C:23
2 B:21
2 B:22
我将此查询的结果集保存在一个临时表 #tt 中,以便以后更简单。
我想要实现的是:
MyID col1 col2 col3
1 A:11__A:21__A:31 C:13__C:23
2 B:21__B:22
但最终的查询会返回:
MyID col1 col2 col3
1 A:11__A:21__A:31__ ________ ____C:13__C:23
2 __ B:21__B:22 __
这是查询:
select
MyID,
col1= stuff((select N'__' + col1 from #tt where MyID = x.MyID for xml path(''), type ).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'' ),
col2= stuff((select N'__' + col2 from #tt where MyID = x.MyID for xml path(''), type ).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'' ),
col2= stuff((select N'__' + col3 from #tt where MyID = x.MyID for xml path(''), type ).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'' )
from #tt as x
group by MyID
如您所见,返回了很多下划线。由于我显示的数据样本较小,因此当我在整个表上运行时会有更多不需要的下划线。看来我正在犯一些我无法弄清楚的小错误。我该如何解决这个问题?
如果我使用的是 SQL Server 2017 或更高版本,string_agg() 可能会有很大帮助。
【问题讨论】:
-
这能回答你的问题吗? Alternative to STRING_AGG in with SQL
标签: sql sql-server concatenation sql-server-2016 sqlxml