sqlserver中的递归查询

mrfwxfqh  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(371)

我有一张结构如下的table
表名: matches
它基本上存储了哪个产品与哪个产品匹配。我需要处理这个表并将其存储在下面的groups表中。
表名: groupsgroup_ID 存储 MIN Product_IDProduct_IDS 形成一个群体。举个例子
若a和b匹配,而b和c匹配,那个么三行应该按格式转到group表 (A, A), (A, B), (A, C) 我试过研究相关联的子查询和cte,但没有实现它。
我需要在sql中完成这一切。
谢谢你的帮助。

jm2pwxwz

jm2pwxwz1#

类似的东西(未测试)

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;
rryofs0p

rryofs0p2#

递归级别示例:

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
kgsdhlau

kgsdhlau3#

试试这个:

;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演示

相关问题