首页 > 技术文章 > 分期值、累计值的相互转换

linyuansun 2020-03-02 23:32 原文


-- 分期值到累计值代码示例1
with temp00 as (
select
'2020-01-01' date1,
1 num1
union all
select
'2020-01-02' adate1,
2 num1
union all
select
'2020-01-03' date1,
3 num1
union all
select
'2020-01-04' date1,
4 num1 )

select
t1.date1 new_date,
sum(t2.num1) new_num
from
temp00 t1
inner join
temp00 t2
on t1.date1>=t2.date1
group by
t1.date1


-- 分期值到累计值代码示例2
with temp00 as (
-- temp00 要保证date1、class1非空、非null,不然没有意义
select
'2020-01-01' date1,
1 num1,
'aa' class1
union all
select
'2020-01-02' date1,
2 num1,
'aa' class1
union all
select
'2020-01-03' date1,
3 num1,
'aa' class1
union all
select
'2020-01-04' date1,
4 num1,
'aa' class1
union all
select
'2020-01-01' date1,
1 num1,
'bb' class1
union all
select
'2020-01-02' date1,
2 num1,
'bb' class1
union all
select
'2020-01-03' date1,
3 num1,
'bb' class1 )

select
t1.date1 new_date,
t1.class1 new_class,
sum(isnull(t2.num1,0)) new_num
from
temp00 t1
left join
temp00 t2
on t1.date1>=t2.date1
and t1.class1=t2.class1
group by
t1.date1,
t1.class1





-- 分期值到累计值代码示例1
with temp00 as (
select
'2020-01-01' date1,
1 num1
union all
select
'2020-01-02' date1,
3 num1
union all
select
'2020-01-03' date1,
6 num1
union all
select
'2020-01-04' date1,
10 num1 )

select
t1.date1 new_date,
max(isnull(t1.num1,0))-max(isnull(t2.num1,0)) new_num
from
temp00 t1
left join
temp00 t2
on t1.date1>t2.date1
group by
t1.date1


-- 分期值到累计值代码示例2
with temp00 as (
-- temp00 要保证date1、class1非空、非null,不然没有意义
select
'2020-01-01' date1,
'aa' class1,
1 num1
union all
select
'2020-01-02' date1,
'aa' class1,
3 num1
union all
select
'2020-01-03' date1,
'aa' class1,
 6 num1
union all
select
'2020-01-04' date1,
'aa' class1,
10 num1
union all
select
'2020-01-01' date1,
'bb' class1,
1 num1
union all
select
'2020-01-02' date1,
'bb' class1,
3 num1
union all
select
'2020-01-03' date1,
'bb' class1,
6 num1 )

select
t1.date1 new_date,
t1.class1 new_class,
max(isnull(t1.num1,0))-max(isnull(t2.num1,0)) new_num
from
temp00 t1
left join
temp00 t2
on t1.date1>t2.date1
and t1.class1=t2.class1
group by
t1.date1,
t1.class1

推荐阅读