暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

SQL Server递归SQL

原创 康斌 2019-08-16
915
-- way1
;with 
t1 as 
(select 1 as iden,'A' as yarn,10 as weight
union all select 2 as iden,'A' as yarn,12 as weight
union all select 3 as iden,'A' as yarn,15 as weight
union all select 4 as iden,'B' as yarn,26 as weight
union all select 5 as iden,'B' as yarn,21 as weight
union all select 6 as iden,'B' as yarn,41 as weight
)
,t2 as
(select 1 as id,'A' as yarn,20.00 as weight
union all select 2 as id,'B' as yarn,38.00 as weight
)
,t3 as 
(select iden,yarn,weight,add_w=sum(weight)over(partition by yarn order by iden) 
from t1
)
select 
t3.iden
,t3.yarn
,weight=case when add_w<=t2.weight then 0 when t3.add_w-t3.weight>=t2.weight then t3.weight else t3.add_w -t2.weight end  
from t3 
left join t2 
on t3.yarn =t2.yarn 
order by iden 
go
-- way2
;with 
t1 as 
(select 1 as iden,'A' as yarn,10 as weight
union all select 2 as iden,'A' as yarn,12 as weight
union all select 3 as iden,'A' as yarn,15 as weight
union all select 4 as iden,'B' as yarn,26 as weight
union all select 5 as iden,'B' as yarn,21 as weight
union all select 6 as iden,'B' as yarn,41 as weight
)
,t2 as
(select 1 as id,'A' as yarn,20.00 as weight
union all select 2 as id,'B' as yarn,38.00 as weight
)
,t11 as (select yid=ROW_NUMBER()over(partition by yarn order by iden),* from t1)
,t3 as 
(select t11.yid,t11.iden ,yarn,weight,weight as add_w from t11 where not exists(select 1 from t11 b where t11.yarn =b.yarn and t11.iden >b.iden)
union all
select t11.yid,t11.iden,t11.yarn,t11.weight,t11.weight +t3.add_w 
from t11 
inner join t3 on t11.yarn =t3.yarn  and t11.yid  =t3.yid +1
)
select 
t3.iden
,t3.yarn
,weight=case when add_w<t2.weight then 0 when t3.add_w-t3.weight>t2.weight then t3.weight else t3.add_w -t2.weight end  
from t3 
left join t2 
on t3.yarn =t2.yarn 
order by iden
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论