上面领导对航材采购又提出了新需求,不仅要显示厂家报价最低价,还要显示次低价,并且还要计算两者的差值。
于是用到了lag函数,帮了大忙。虽然通过表与表自身连接,也能计算出差值,但是网上说效率lag函数高。
好了,lag 和lead 这两个分析函数,稍稍整理一下。以下是网上转的:
lag 和lead 可以 获取结果集中,按一定排序所排列的当前行的上下相邻若干offset 的某个行的某个列 (不用结果集的自关联);
lag ,lead 分别是向前,向后;
lag 和lead 有三个参数,第一个参数是列名,第二个参数是偏移的offset,第三个参数是 超出记录窗口时的默认值)
举例如下:
SQL> select * from kkk;
ID NAME
---------- --------------------
1 1name
2 2name
3 3name
4 4name
5 5name
SQL> select id,name,lag(name,1,0) over ( order by id ) from kkk;
ID NAME LAG(NAME,1,0)OVER(ORDERBYID)
---------- -------------------- ----------------------------
1 1name 0
2 2name 1name
3 3name 2name
4 4name 3name
5 5name 4name
SQL> select id,name,lead(name,1,0) over ( order by id ) from kkk;
ID NAME LEAD(NAME,1,0)OVER(ORDERBYID)
---------- -------------------- -----------------------------
1 1name 2name
2 2name 3name
3 3name 4name
4 4name 5name
5 5name 0
SQL>
SQL> select id,name,lead(name,2,0) over ( order by id ) from kkk;
ID NAME LEAD(NAME,2,0)OVER(ORDERBYID)
---------- -------------------- -----------------------------
1 1name 3name
2 2name 4name
3 3name 5name
4 4name 0
5 5name 0
SQL>
SQL> select id,name,lead(name,1,'alsdfjlasdjfsaf') over ( order by id ) from kkk;
ID NAME LEAD(NAME,1,'ALSDFJLASDJFSAF')
---------- -------------------- ------------------------------
1 1name 2name
2 2name 3name
3 3name 4name
4 4name 5name
5 5name alsdfjlasdjfsaf
根据函数方法,将每组次低价与最低价差值,新增到差价表的SQL语句即如下:
insert into vender_price_diff
(select com_no, pn, (final_rmb_price - lowest_price) price_diff
from (select t.com_no,
t.pn,
t.vender,
t.final_rmb_price,
lag(t.final_rmb_price, 1, t.final_rmb_price) over(partition by t.com_no, t.pn order by t.final_rmb_price) lowest_price,
t.second_lowest_price
from vender_comparison_detail t
where t.com_no = :comNo)
where second_lowest_price = 'X')