简单调用自身销量并循环计算的问题:
已知2020年1月的销量和2020年2月-6月的环比,求一步到位求出2020年2月-6月的销量?
2020年1月的销量
2020年2月-6月的环比
博主之前考虑的是月份少直接写多次左连接,计算每个月的销量计算,月份多的时候写循环实现,发现有递归写法,语句简便很多。
--1.递归简单用法,熟悉一下
;with ids as (
select 0 as id
union all
select id+1 from ids where id<50
) select * from ids
--2.销量环比计算
;with x1 as (
select '202002' dates,'-0.1532' value union all --2020年2-6月环比
select '202003','0.2417' union all
select '202004','0.1325' union all
select '202005','0.3094' union all
select '202006','0.8837'
), months as (
select 202001 month,cast('342' as float) amount,0 n --2020年1月的销量
union all --递归调用months表的month,amount和n字段,保持union all前后字段类型一致,n作为递归次数控制条件
select cast(month as int)+1,cast(amount*(1+cast(value as float)) as float) amount,n+1 from months a1 inner join x1 a2
on a1.month=cast(a2.dates as int)-1 and a1.n<=5
) select * from months
运行结果:
计算结果验证:
注:如果有更简便的方法,希望可以评论告诉我,萌新在线求教^..^