我有下表,由“CaseID”列排序。
我需要以下面显示的方式打印输出,其中所有结果都使用逗号分组在一起。我写了下面的查询来获取其他所有内容但不确定如何附加所有结果。
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
我怎样才能做到这一点?请指教。
答案 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]