如何在一行中打印相同记录的多个结果?

时间:2016-08-14 13:48:09

标签: sql sql-server sql-server-2012 common-table-expression string-function

我有下表,由“CaseID”列排序。

enter image description here

我需要以下面显示的方式打印输出,其中所有结果都使用逗号分组在一起。我写了下面的查询来获取其他所有内容但不确定如何附加所有结果。

SELECT 
    c.CaseID AS 'Case #',
    c.EventDate AS 'Date',
    CONCAT(d.DrugName+'-',m.ManufacturerName) AS 'Drug & Manufacturer',
    CONCAT(CONVERT(VARCHAR(10),c.Age)+' ',a.AgeUnitName) AS 'Age',
    c.Sex,
    ou.OutcomeName
FROM
    Consumes con
INNER JOIN 
    [Case] c ON con.FKCaseID = c.CaseID
INNER JOIN 
    Drug d ON d.DrugID = FKDrugID
INNER JOIN 
    Manufacturer m ON m.ManufacturerID = con.FKManufacturerID
INNER JOIN 
    AgeUnit a ON a.AgeUnitID = c.FKAgeUnitID
INNER JOIN 
    Case_Outcome oc ON oc.FKCaseID = c.CaseID
INNER JOIN 
    OutCome ou ON oc.FKOutcomeID = ou.OutcomeID
GROUP BY   
    c.CaseID, c.EventDate, d.DrugName, 
    m.ManufacturerName, c.Age, a.AgeUnitName, c.Sex, ou.OutcomeName

enter image description here

我怎样才能做到这一点?请指教。

1 个答案:

答案 0 :(得分:1)

将您的所有查询都放入CTE,然后使用FOR XML

;WITH cte AS (
--your query goes here
)

SELECT c.[Case #],
       c.[Date],
       c.[Drug & Manufacturer],
       c.[Age],
       c.[Sex],
       STUFF((SELECT ','+OutcomeName
       FROM cte
       WHERE c.[Case #] = [Case #]
       FOR XML PATH('')),1,1,'') as OutcomeName
FROM cte c
GROUP BY c.[Case #],
       c.[Date],
       c.[Drug & Manufacturer],
       c.[Age],
       c.[Sex]
相关问题
最新问题