首页 > 解决方案 > 向 CTE 添加子查询

问题描述

declare @nodeid int = '1';

with cte as 
(
    select  
        cust_ID, name, null lnode, null rnode 
    from  
        user_detail 
    where 
        cust_ID = @nodeid 

    union all 

    select 
        t.cust_ID, t.name, 
        isnull(cte.lnode, case when t.joinside = 0 then 1 else 0 end) 
        lnode, 
        isnull(cte.rnode, case when t.joinside = 1 then 1 else 0 end),
        rnode 
    from  
        user_detail t 
    inner join 
        cte on cte.cust_ID = t.parentid 
)
select 
    cust_ID, name 
from 
    cte 
where 
    rnode = '0' 
option (maxrecursion 0)

当前情景:

在此处输入图像描述

我想要的是:

在此处输入图像描述

我将解释我想要什么:上面的查询仅从user_detail表中获取结果。我想以这样一种方式修改查询,它还将在installments表中搜索status相应的列cust_id

修改后的查询将从基于的分期付款表中获取状态值cust_id

查询将在第三列中显示结果,如第二个屏幕截图所示。

我对 CTE 和嵌套查询不是很熟悉。我希望你们能理解我的问题。

标签: sqltsql

解决方案


你可以试试下面 -

declare @nodeid int = '1';
with cte as ( 
select  cust_ID, name,null lnode, null rnode from  user_detail where 
cust_ID = @nodeid 

union all select t.cust_ID,t.name, ISNULL(cte.lnode, CASE WHEN t.joinside = 
0 THEN 1 ELSE 0 END) 
lnode, ISNULL(cte.rnode, CASE WHEN t.joinside = 1 THEN 1 ELSE 0 END) 
rnode from  user_detail t inner join cte on cte.cust_ID = t.parentid )

select cust_ID,name,status from cte c
inner join installment i on c.cust_id=i.cust_id
where rnode='0' 
option (maxrecursion 0)

推荐阅读