0

我最近被介绍给 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]

结果:

在此处输入图像描述

请帮忙。

4

1 回答 1

0

您的数据是重复的,因为您正在将 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]

下面是东西的解释:

Stuff 和“用于 Xml 路径”如何在 SQL Server 中工作?

于 2021-08-27T22:53:50.123 回答