首先,创建一些test_table的测试表,这个表有三个字段,分别为区域,年月和数量。
sql语句如下:
create table TEST_TABLE(
Region varchar2(20),
yearmouth number(6),
amount number(10,2)
)
再插入一些测试数据,如下:
第一种方法,可以用LAG函数俩获取上个月的数据,先添加一个上月的数量字段,sql语句如下:
merge into TEST_TABLE t1
using (select
t2.region,
t2.yearmouth,
Lag(t2.amount, 1, null) over(PARTITION BY t2.region order by t2.yearmouth) as last_mouth_amout
from TEST_TABLE t2
) t3
on (t1.region = t3.region and t1.yearmouth = t3.yearmouth)
WHEN MATCHED THEN
UPDATE SET
t1.last_mouth_amount = t3.last_mouth_amout;
commit;
得到的结果如下:
第二种方法,将年月这个字段减去1,得到上个月,sql语句如下:
SELECT t1.yearmouth - 1 AS yearmouth,
t1.region as region,
t1.amount as last_month_amount
from test_table t1;
结果如下:
sql语句如下:
create table TEST_TABLE(
Region varchar2(20),
yearmouth number(6),
amount number(10,2)
)
再插入一些测试数据,如下:
第一种方法,可以用LAG函数俩获取上个月的数据,先添加一个上月的数量字段,sql语句如下:
merge into TEST_TABLE t1
using (select
t2.region,
t2.yearmouth,
Lag(t2.amount, 1, null) over(PARTITION BY t2.region order by t2.yearmouth) as last_mouth_amout
from TEST_TABLE t2
) t3
on (t1.region = t3.region and t1.yearmouth = t3.yearmouth)
WHEN MATCHED THEN
UPDATE SET
t1.last_mouth_amount = t3.last_mouth_amout;
commit;
得到的结果如下:
第二种方法,将年月这个字段减去1,得到上个月,sql语句如下:
SELECT t1.yearmouth - 1 AS yearmouth,
t1.region as region,
t1.amount as last_month_amount
from test_table t1;
结果如下: