本文转自
有如下一个表
WITH t AS
(
SELECT 1 rn, 3.0 V
UNION ALL SELECT 2, 4.5
UNION ALL SELECT 3, 6.0
UNION ALL SELECT 4, 11.0
UNION ALL SELECT 5, 3.0
)
select * from t
DEC1.png
rn 代表顺序,V代表积分
现有这样一个需求。需要扣除11分,从rn = 1开始扣,扣完为止。
先利用窗口函数,求得累计值
WITH t AS
(
SELECT 1 rn, 3.0 V
UNION ALL SELECT 2, 4.5
UNION ALL SELECT 3, 6.0
UNION ALL SELECT 4, 11.0
UNION ALL SELECT 5, 3.0
)
select 11 as decV,sum(v) over(order by rn) as ljV,rn,V from t
DEC2.png
decV 代表要扣除的值,ljV 代表累计值。V代表每行的值。通过这三个值进行操作就可以得到我们想到的结果啦
我们先求每行要用掉的分
如果累计值 <= 要扣除的值,则该行值需要全部扣除
如果累计值 - 本行值 已大于要扣除的值 ,则该行不需要扣除
如果累计值 - 本行值 小于要扣除的值 ,则该行只需扣除部份
最终语句如下
WITH t AS
(
SELECT 1 rn, 3.0 V
UNION ALL SELECT 2, 4.5
UNION ALL SELECT 3, 6.0
UNION ALL SELECT 4, 11.0
UNION ALL SELECT 5, 3.0
)
select rn,v,ljV,decV,
case when ljV <= decv then V else
case when ljV- V < decv then decV-ljV + V else 0 end
end as usedV,
case when ljV <= decv then 0 else
case when ljV - V < decV then ljV-decV else V end
end as residueV
from
(
select 11 as decV,sum(v) over(order by rn) as ljV,rn,V from t
) as t1
DEC3.png
usedV 代表该行扣除的值
residueV 代表该行剩余的值
作者:老骥
链接:https://www.jianshu.com/p/850ad5429bf4
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。