您可以使用公用表表达式轻松完成此操作。您将使用 FOR XML PATH 创建一个数组,然后使用该数组来识别匹配的产品。像这样:
;WITH AreaProductSets
AS
(
SELECT a.AreaID, a.Name,
SUBSTRING((SELECT (', ' + CAST(ap.ProductID AS varchar(20)))
FROM AreaToProduct ap
WHERE ap.AreaID = a.AreaID
ORDER BY ap.ProductID
FOR XML PATH ('')), 3, 2000) AS ProductArray
FROM Area AS a
)
SELECT SUBSTRING((SELECT (', ' + CAST(aps2.Name AS varchar(20)))
FROM AreaProductSets aps2
WHERE aps2.ProductArray = aps.ProductArray
ORDER BY aps2.AreaID
FOR XML PATH('')), 3, 2000) AS MatchingAreas,
aps.ProductArray
FROM (SELECT DISTINCT ProductArray FROM AreaProductSets) AS aps