gpt4 book ai didi

sql - 使用递归公用表表达式从两个表中查找连续编号

转载 作者:行者123 更新时间:2023-12-04 22:24:39 25 4
gpt4 key购买 nike

我有以下表格:

Actual         Optional
------ --------
4 3
13 6
20 7
26 14
19
21
27
28

我要做的是选择:

1) all the values from "Actual" Table.

2) select values from "Optional" table if they form a consecutive series with "actual" table values



预期的结果是:
Answer
------
4
13
20
26
3 --because it is consecutive to 4 (i.e 3=4-1)
14 --14=13+1
19 --19=20-1
21 --21=20+1
27 --27=26+1
28 --this is the important case.28 is not consecutive to 26 but 27
--is consecutive to 26 and 26,27,28 together form a series.

我使用递归 cte 编写了一个查询,但它永远循环并在递归达到 100 级后失败。
我面临的问题是 27 场比赛与 26、28 场比赛与 27 和 27 与 28.again 28 与 27 ......(永远)

这是我写的查询:
with recurcte as
(
select num as one,num as two from actual
union all
select opt.num as one,cte.two as two
from recurcte cte join optional opt
on opt.num+1=cte.one or opt.num-1=cte.one
)select * from recurcte

最佳答案

;WITH Combined
AS (SELECT 1 AS Actual, N
FROM (VALUES(4),
(13),
(20),
(26)) Actual(N)
UNION ALL
SELECT 0 AS Actual, N
FROM (VALUES(3),
(6),
(7),
(14),
(19),
(21),
(27),
(28)) Optional (N)),
T1
AS (SELECT *,
N - DENSE_RANK() OVER (ORDER BY N) AS Grp
FROM Combined),
T2
AS (SELECT *,
MAX(Actual) OVER (PARTITION BY Grp) AS HasActual
FROM T1)
SELECT DISTINCT N
FROM T2
WHERE HasActual = 1

关于sql - 使用递归公用表表达式从两个表中查找连续编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7362978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com