SQL 對比,移動累計

數據對比 兩種經常使用模型

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.累計上個結果 (諾依曼型遞歸集合)spa

-- 建表
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;
相關文章
相關標籤/搜索