SQL Server中的递归查询

时间:2013-01-25 08:34:12

标签: sql sql-server

我有一个包含以下结构的表

表名:matches

Table name: matches

基本上存储哪个产品匹配哪个产品。我需要处理这个表 并存储在下面的组表中。

表名:groups

enter image description here

group_ID存储组成组的MIN Product_ID Product_IDS。举个例子,让我们说

如果A匹配B且B匹配C,那么三行应该以格式(A, A), (A, B), (A, C)

的形式转到组表

我已经尝试过查看与co-related相关的子查询和CTE,但是没有让它实现。

我需要在SQL中完成所有这些操作。

感谢您的帮助。

3 个答案:

答案 0 :(得分:51)

试试这个:

;WITH CTE
AS
(
    SELECT DISTINCT
        M1.Product_ID Group_ID,
        M1.Product_ID
    FROM matches M1
        LEFT JOIN matches 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 C
        JOIN matches M
            ON C.Product_ID = M.Product_ID
)
SELECT * FROM CTE ORDER BY Group_ID

您可以使用OPTION(MAXRECURSION n)来控制递归深度。

<强> SQL FIDDLE DEMO

答案 1 :(得分:1)

像这样(未经测试)

with match_groups as (

  select product_id, 
         matching_product_id,
         product_id as group_id
  from matches
  where product_id not in (select matching_product_id from matches)

  union all

  select m.product_id, m.matching_product_id, p.group_id
  from matches m
    join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;

答案 2 :(得分:1)

递归级别的示例:

enter image description here

DECLARE @VALUE_CODE AS VARCHAR(5);

--SET @VALUE_CODE = 'A' -- Specify a level

WITH ViewValue AS
(
    SELECT ValueCode
    , ValueDesc
    , PrecedingValueCode
    FROM ValuesTable
    WHERE PrecedingValueCode IS NULL
    UNION ALL
    SELECT A.ValueCode
    , A.ValueDesc
    , A.PrecedingValueCode 
    FROM ValuesTable A
    INNER JOIN ViewValue V ON
        V.ValueCode = A.PrecedingValueCode
)

SELECT ValueCode, ValueDesc, PrecedingValueCode

FROM ViewValue

--WHERE PrecedingValueCode  = @VALUE_CODE -- Specific level

--WHERE PrecedingValueCode  IS NULL -- Root