【发布时间】:2020-06-23 16:57:38
【问题描述】:
我正在尝试基于相同的 ID 合并 2 列,但遇到一个问题,即 2 列中的任何一个为空值会使结果为空
数据看起来像这样
ID Notes Date
-----------------------
1 notes1 3/1/20
1 notes2 3/2/20
1 notes3 3/3/20
2 notes1
2 notes2
期望的输出
Id CombinedNotes
-------------------------------------------------------------------------
1 Date: 3/1/20 Notes: Notes1 Date: 3/2/20 Notes: Notes2 Date: 3/3/20 Notes: Notes3
2 Date: NUll Notes: Notes1 Date: Null Notes: Notes2
实际电流输出为:
Id CombinedNotes
-----------------------------------------------------------------------------
1 Date: 3/1/20 Notes: Notes1 Date: 3/2/20 Notes: Notes2 Date: 3/3/20 Notes: Notes3
2 Null
我正在运行这个查询
SELECT DISTINCT
t2.[id],
STUFF ((SELECT ' Date: ' + t1.[date] + ' Notes:' + [notes]
FROM [dbo].[test1] t1
WHERE t1.[id] = t2.[id]
FOR XML PATH ('')), 1, 2, '')
FROM
[dbo].[test1] t2
结果如下所示:
我应该改变什么,如果它是空白的,是否可以没有这样的“日期:”,所以所需的输出看起来像这样
2 Notes: Notes1 Notes: Notes2
谢谢
【问题讨论】:
-
您的 SQL Server 版本是多少?
-
function
CONCAT()比简单的+连接更智能...
标签: sql sql-server xml concatenation ssms