如何连接SSRS中多行的文本?

how to concatenate text from multiable rows in SSRS?

我最近接触了 SSRS,但在从数据库中提取数据时遇到了问题。 我在网上搜索了一下,发现这叫做从多行中连接文本。现在,我尝试了一个代码……但在结果中,它给我提供了彼此相邻的重复数据,并用逗号分隔。现在我很高兴它用昏迷分隔结果......但为什么给我重复的数据?

代码:

select distinct wm1.Date, p1.[Medical Record Number], Wound_Type =CONCAT
((
select distinct  CAST(wt2.Name as VARCHAR(MAX))+ ' /// ' from dbo.[Wound Type] as wt2
inner join dbo.[Wound Management] as wm2 on wm2.[Wound Type_ID] = wt2.ID
inner join dbo.Patient as p2 on wm2.[Owner (Patient)_Patient_ID]=p2.ID
where wm1.Date=wm2.Date
FOR XML PATH('')
),wt1.Name)
from dbo.[Wound Type] as wt1
inner join dbo.[Wound Management] as wm1 on wm1.[Wound Type_ID] = wt1.ID
inner join dbo.Patient as p1 on wm1.[Owner (Patient)_Patient_ID]=p1.ID
group by wm1.Date, wt1.Name, p1.[Medical Record Number]

结果:

请帮忙。

您的数据重复,因为您将 wt2.Names 的列表与 wt1.Name - ,wt1.Name) 的列表合并。日期为 NULL 的那个没有找到匹配的记录,只显示 wt1.Name

实际上我认为您可能希望使用 STUFF 函数而不是 CONCAT 来删除末尾的任何额外斜线。

SELECT DISTINCT wm1.Date, p1.[Medical Record Number], Wound_Type = STUFF( 
    (
    SELECT DISTINCT ' /// ' + CAST(wt2.Name as VARCHAR(MAX)) 
    from dbo.[Wound Type] as wt2
    inner join dbo.[Wound Management] as wm2 on wm2.[Wound Type_ID] = wt2.ID
    inner join dbo.Patient as p2 on wm2.[Owner (Patient)_Patient_ID]=p2.ID
    where wm1.Date=wm2.Date
    FOR XML PATH('')
    ), 1, 5, '' )
from dbo.[Wound Type] as wt1
inner join dbo.[Wound Management] as wm1 on wm1.[Wound Type_ID] = wt1.ID
inner join dbo.Patient as p1 on wm1.[Owner (Patient)_Patient_ID]=p1.ID
group by wm1.Date, wt1.Name, p1.[Medical Record Number]

这不能解决 NULL 日期问题。您可以将 STUFF 包装在 ISNULL 中。

SELECT DISTINCT wm1.Date, p1.[Medical Record Number], Wound_Type = ISNULL(STUFF( 
    (
    SELECT DISTINCT ' /// ' + CAST(wt2.Name as VARCHAR(MAX)) 
    from dbo.[Wound Type] as wt2
    inner join dbo.[Wound Management] as wm2 on wm2.[Wound Type_ID] = wt2.ID
    inner join dbo.Patient as p2 on wm2.[Owner (Patient)_Patient_ID]=p2.ID
    where wm1.Date=wm2.Date
    FOR XML PATH('')
    ), 1, 5, '' )
    , wt1.Name)
from dbo.[Wound Type] as wt1
inner join dbo.[Wound Management] as wm1 on wm1.[Wound Type_ID] = wt1.ID
inner join dbo.Patient as p1 on wm1.[Owner (Patient)_Patient_ID]=p1.ID
group by wm1.Date, wt1.Name, p1.[Medical Record Number]

这里有一些解释:

How Stuff and 'For Xml Path' work in SQL Server?