我已经将一个脚本从MySQL修改为SQL Server,并且大部分都正确地更改了脚本,但是遇到了最后一点语法问题。在对STUFF FOR XML PATH
语句中的子查询执行相同操作之后,我尝试FROM
到脚本顶部的查询。子查询正常工作,它是我遇到问题的主要查询。整个脚本相当大,所以我只是把它放在rextester.com
我希望我在我的问题中有意义,因为我想要获得的结果是Complete_Codes
和Incomplete_Codes
在facility_priority
和{{1}的同一行上一起。
提前谢谢!
答案 0 :(得分:1)
在GROUP BY查询的SELECT列表中使用FOR XML PATH的子查询应该遵循模板
SELECT
c1.facility_name,
c1.facility_priority,
STUFF((SELECT ',' + c2.Incomplete_Codes
FROM combined c2
WHERE c2.facility_name = c1.facility_name AND c2.facility_priority =c1.facility_priority
FOR XML PATH('')), 1, 1, '') AS Incomplete
FROM combined c1
GROUP BY
facility_name,
facility_priority
因此,您的内部查询可以作为CTE引入。最后
WITH combined AS (
-- your inner query
)
SELECT
c1.facility_name,
c1.facility_priority,
STUFF((SELECT ',' + c2.Incomplete_Codes
FROM combined c2
WHERE c2.facility_name = c1.facility_name AND c2.facility_priority =c1.facility_priority
FOR XML PATH('')), 1, 1, '') AS Incomplete
--, same for complete
FROM combined c1
GROUP BY
facility_name,
facility_priority