一佳一

记录像1+1一样简洁的代码

导航

SQL 对比,移动累计

Posted on 2019-07-23 11:15  一佳一  阅读(310)  评论(0编辑  收藏  举报

数据对比 两种常用模型

1.对比下一行,判断增长、减少、维持现状

-- 建表
drop table sales

create table sales(
num int,
soc int
);
insert into sales values(1, 70);
insert into sales values(2, 60);
insert into sales values(3, 50);
insert into sales values(4, 50);
insert into sales values(5, 51);
insert into sales values(6, 52);
insert into sales values(7, 50);
insert into sales values(8, 40);

select a.num, a.soc,
       case when a.soc = b.soc then '0'  -- 持平
            when a.soc > b.soc then '+'  -- 增长
            when a.soc < b.soc then '-'  -- 减少
       else '-' end as var
  from sales a left join sales b
    on a.num = b.num + 1 
 order by num

 

2.累计上个结果 (诺依曼型递归集合)

-- 建表
drop table if exists accounts;
create table accounts(
prc_date date,
prc_amt int8
);
insert into accounts values(20061026,12000);
insert into accounts values(20061028,2500);
insert into accounts values(20061031,-15000);
insert into accounts values(20061103,34000);
insert into accounts values(20061104,-5000);
insert into accounts values(20061106,7200);
insert into accounts values(20061111,11000);

--测试

select prc_date, a1.prc_amt,
(select sum(prc_amt) from accounts a2
where a1.prc_date >= a2.prc_date) as onhand_amt
from accounts a1
order by prc_date;