【问题标题】:How to concatenate column data in SQL Server 2016?如何在 SQL Server 2016 中连接列数据?
【发布时间】: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() 可能会有很大帮助。

【问题讨论】:

标签: sql sql-server concatenation sql-server-2016 sqlxml


【解决方案1】:

过滤掉子查询中的空值或NULL

... from #tt where MyID = x.MyID AND col1 IS NOT NULL AND col1 <> '' ...

(以及col2col3 的模拟。)

【讨论】:

    【解决方案2】:

    这是你想去的地方吗?

    SELECT
        MyID,
        col1 = ISNULL(STUFF((SELECT N'__' + NULLIF(col1, '') FROM #tt WHERE MyID = x.MyID FOR XML PATH(''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N''), ''),
        col2 = ISNULL(STUFF((SELECT N'__' + NULLIF(col2, '') FROM #tt WHERE MyID = x.MyID FOR XML PATH(''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N''), ''),
        col2 = ISNULL(STUFF((SELECT N'__' + NULLIF(col3, '') FROM #tt WHERE MyID = x.MyID FOR XML PATH(''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N''), '')
    FROM
        #tt x
    GROUP BY
        MyID;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多