是否可以在此示例中使用递归 CTE?
Is it possible to utilize Recursive CTE in this example?
IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP TABLE #MyTable
create table #MyTable (PolNo varchar(50), ControlNo int, PrevControlNo int, Premim money)
insert into #MyTable values ('Policy-00', 5000, NULL, 1000),
('Policy-01', 6000, 5000, 3200),
('Policy-02', 7000, 6000, 4500),
('Policy-03', 8000, 7000, 3800)
select * from #MyTable
原始输出如下所示:
使用递归CTE是否可以得到如下结果?
我试过类似的方法,但它基本上给了我相同的结果:
;with cte as (
select m.PolNo, m.ControlNo, PrevControlNo, 1 as lvl
from #MyTable m
union all
select c.PolNo, c.ControlNo, c.PrevControlNo, c.lvl+1
from cte c
inner join #MyTable m ON m.ControlNo = c.PrevControlNo
where c.PrevControlNo IS NULL
)
select cte.PolNo, ControlNo, PrevControlNo
from cte
LEFT JOIN
单关就够了:
SELECT *
FROM #MyTable m1
LEFT JOIN #MyTable m2
ON m2.ControlNo = m1.PrevControlNo;
IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP TABLE #MyTable
create table #MyTable (PolNo varchar(50), ControlNo int, PrevControlNo int, Premim money)
insert into #MyTable values ('Policy-00', 5000, NULL, 1000),
('Policy-01', 6000, 5000, 3200),
('Policy-02', 7000, 6000, 4500),
('Policy-03', 8000, 7000, 3800)
select * from #MyTable
原始输出如下所示:
使用递归CTE是否可以得到如下结果?
我试过类似的方法,但它基本上给了我相同的结果:
;with cte as (
select m.PolNo, m.ControlNo, PrevControlNo, 1 as lvl
from #MyTable m
union all
select c.PolNo, c.ControlNo, c.PrevControlNo, c.lvl+1
from cte c
inner join #MyTable m ON m.ControlNo = c.PrevControlNo
where c.PrevControlNo IS NULL
)
select cte.PolNo, ControlNo, PrevControlNo
from cte
LEFT JOIN
单关就够了:
SELECT *
FROM #MyTable m1
LEFT JOIN #MyTable m2
ON m2.ControlNo = m1.PrevControlNo;