我有一个返回服务列表和ContractorID的查询。我需要将这些服务填充到一个字段中,以便通过ContractorID将它们与另一个select语句连接起来,但我无法弄清楚如何去做。
列出服务的选择是“
SELECT DISTINCT SM.ContractorID,
CASE WHEN S.bitRestrictedSelection = 1
THEN S.vchDescription + '*'
ELSE S.vchDescription
END AS vchDescription
FROM tblAscServiceRegionToOperator SRTO
INNER JOIN tblServiceMatrix SM
ON SRTO.OperatorID = 12624
AND SM.ServiceRegionID = SRTO.ServiceRegionID
AND SM.bitPrimaryService = 1
INNER JOIN tblServices S
ON S.ServiceID = SM.ServiceID
这会产生以下结果:
在示例中,对于Contractor#16,他有4个服务,我需要通过加入另一个Select语句将它们放在一个名为services的字段中 我尝试了以下方法,但是我收到了错误:
Select DISTINCT CompanyID, vchCompanyName as CompanyName,vchFIDNumber,vchPrimContactName, vchPrimContactEmail
,stuff((','
SELECT DISTINCT
SM.ContractorID,
CASE WHEN S.bitRestrictedSelection = 1
THEN S.vchDescription + '*'
ELSE S.vchDescription
END AS vchDescription
FROM tblAscServiceRegionToOperator SRTO
INNER JOIN tblServiceMatrix SM
ON SRTO.OperatorID = 12624
AND SM.ServiceRegionID = SRTO.ServiceRegionID
AND SM.bitPrimaryService = 1
INNER JOIN tblServices S
ON S.ServiceID = SM.ServiceID
FOR XML PATH('')
), 1, 1, '') as Services from tblCompany
非常感谢任何帮助!!!
答案 0 :(得分:4)
以下查询可行:
SELECT SS.contractor Contractor,
STUFF((SELECT '; ' + US.vchdescription
FROM ServicesList US
WHERE US.contractor = SS.contractor
FOR XML PATH('')), 1, 1, '') [Services]
FROM ServicesList SS
GROUP BY SS.contractor
ORDER BY 1
我已经创建了一个表并在那里插入了两行,用于承包商= 16,以便您了解。
您可以在评论中使用给出的建议,将第一个选项包装到CTE
,然后在STUFF
上执行CTE
函数。
您可以查看此查询的演示here。