Recursive Query in SQL Server
A table named 'matches' stores product pairings, where one product matches another. The goal is to create a 'groups' table that identifies product groups consisting of all products that match each other. The group ID should store the minimum product ID in each group.
Recursive CTE Solution
To achieve this, we can employ a recursive Common Table Expression (CTE) as follows:
WITH CTE AS ( SELECT DISTINCT M1.Product_ID AS Group_ID, M1.Product_ID FROM matches AS M1 LEFT JOIN matches AS M2 ON M1.Product_Id = M2.matching_Product_Id WHERE M2.matching_Product_Id IS NULL UNION ALL SELECT C.Group_ID, M.matching_Product_Id FROM CTE AS C JOIN matches AS M ON C.Product_ID = M.Product_ID ) SELECT * FROM CTE ORDER BY Group_ID;
The CTE recursively finds all products that are directly or indirectly related to each other. It starts by identifying products with no matching products (Group_ID is their own Product_ID). Then, it retrieves all matching products for each group, adding them to the CTE. The UNION ALL clause combines the results of the initial query with the results of subsequent iterations, ensuring that all matching products are found.
The ORDER BY Group_ID clause arranges the results in ascending order of group ID, providing an easy way to identify product groups and their members.
Customizing Recursion Depth
Using the OPTION(MAXRECURSION n) clause, we can control the maximum recursion depth, which helps prevent excessive recursion in cases with complex product relationships.
Demo
For a detailed demonstration, refer to the SQL Fiddle example:
https://www.sqlfiddle.com/#!17/d4e0f/20332
The above is the detailed content of How Can Recursive CTEs Identify Product Groups in SQL Server Based on Matching Pairs?. For more information, please follow other related articles on the PHP Chinese website!