使用Stuff()函数组合多行

时间:2016-12-28 18:24:10

标签: sql-server

我已经阅读了stuff()函数的帖子,我相信这是我应该用于查询的函数。

但是,我需要在此帖子中进一步采用示例并添加更多列,并包含一个子查询,该查询从另一个表中提取与我的原因ID匹配的原因文本。我有一个表格,其中包含日期,患者ID,原因,其他注释......我需要将每位患者和每个日期的所有注释/原因合并为一列,以便:

Date        patientID       reason .....other columns....
__________________________________________________________
12/26/2016   2              age
12/26/2016   2              location
12/27/2016   2              missing info
12/27/2016   2              age

变为

Date        patientID       reason .....other columns....
__________________________________________________________
12/26/2016   2              age, location
12/27/2016   2              missing info, age

这是我开始创建的内容,但它给了我患者的所有理由,而不仅仅是那些属于约会的人。另外,我不知道如何添加到查询中来拉取其余列。

请帮我创建一个很好的强查询。

     SELECT distinct DATEADD(dd, DATEDIFF(dd, 0, dateAdded), 0), 
            otherNote = STUFF((SELECT ', ' + (CASE WHEN eligibilityReason= 7 
            THEN otherNote ELSE Reasons.reason end) as reason 
            FROM Eligibility left Join Reasons on Reasons.reasonID = eligibilityReason 
            WHERE patientID=2 
                FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)'), 1, 2, '')
            FROM Eligibility 
            GROUP BY DATEADD(dd, DATEDIFF(dd, 0, dateAdded), 0)

1 个答案:

答案 0 :(得分:0)

您需要将子查询与外部查询相关联。

SELECT distinct 
      DATEADD(dd, DATEDIFF(dd, 0, eg.dateAdded), 0)
    , otherNote = STUFF(( SELECT ', ' + (CASE WHEN e.eligibilityReason= 7 
                                                THEN e.otherNote 
                                            ELSE r.reason 
                                        end) as reason 
                          FROM Eligibility e
                          left Join Reasons on r.reasonID = e.eligibilityReason 
                          where eg.patientID = e.patientID  --<-- Correlate
                          AND  eg.[Date] = e.[Date]         --<-- Correlate
                          FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)'), 1, 2, '')
FROM Eligibility eg
GROUP BY DATEADD(dd, DATEDIFF(dd, 0, eg.dateAdded), 0)