在CTE查询中,根据第一个表检索到的ID对另一个表中的记录进行计数

时间:2019-04-29 06:50:36

标签: sql sql-server

我正在研究基于CTE的查询。我以前从未使用过。我正在使用以下查询,该查询从user_detail表中获取记录。

 with cte as ( select  cust_ID, parentid, name, joinside,regdate,package,null lnode, null rnode from  user_detail 
 where cust_ID = @nodeid 
 union all select t.cust_ID, t.parentid,t.name, t.joinside,t.regdate,t.package, 
 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 @nodeid nodeid,name,cust_ID,parentid,regdate,package from cte 

 where rnode='0' order by cust_id asc option (maxrecursion 0)

上面的查询给了我6列(nodeid,name,cust_ID,parentid,regdate,package)。 现在我真正想要的是,我想要第7列,该列将基于来自另一表分期付款的cust_id来计算行数。

我正在做下面的事情,但是当我在查询中添加group by时,它给了我错误。

 declare @nodeid int = '1';
 with cte as ( select  cust_ID, parentid, name, joinside,regdate,package,null lnode, null rnode from  user_detail 
 where cust_ID = @nodeid 
 union all select t.cust_ID, t.parentid,t.name, t.joinside,t.regdate,t.package, 
 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 @nodeid nodeid,name,ctttt.cust_ID,parentid,regdate,package,insttt.cust_id from cte as ctttt left join installments as insttt 
 on ctttt.cust_id = insttt.cust_id

 where rnode='0' order by ctttt.cust_id asc option (maxrecursion 0)

1 个答案:

答案 0 :(得分:0)

使用batch_input_shape

sub query

查询:

 (select count(*) from installments as insttt  where  ctttt.cust_id = insttt.cust_id ) cnt