我有一个包含值的3行表:
Row1 : 5
Row2 : 8
Row3 : 9
我想计算增加或减少的百分比:Row2与Row1,Row3相比Row2所以我会有这个表:
计算%的公式为:[Row(n+1) - Row(n)] / Row(2)
Value Percentage
Row1 : 5 -
Row2 : 8 60% (increase compared to Row1) | (8-5)/5
Row3 : 9 12.5%(increase compared to Row2)| (9-8)/8
请建议方法或解决方案。
谢谢大家。
答案 0 :(得分:6)
您需要使用Oracle Analytical函数LAG:
您的查询类似于:
SELECT ((value - lagv)/lagv) * 100
FROM (
SELECT value,
LAG(value) OVER(ORDER BY <ordering_column>) as lagv
FROM table1
);
测试我跑:
WITH t AS (SELECT 1 as rnum,
5 AS value FROM DUAL
UNION
SELECT 2 as rnum,
8 AS value FROM DUAL
UNION
SELECT 3 as rnum,
9 AS value FROM DUAL
)
SELECT ((value - lagv)/lagv) * 100 AS Percentage
FROM (
SELECT value,
LAG(value) OVER(ORDER BY rnum) as lagv
FROM t
);
它返回了:
Row Percentage
1
2 60
3 12.5
由于你需要为我创建了rnum列的LAG函数指定一个订单,我假设你的表有一些你可以使用的排序列,(否则你怎么知道要比较哪些行?)。
希望这会有所帮助......
编辑:此链接对于了解Oracle的LEAD和LAG功能非常有用。 http://www.oracle-base.com/articles/misc/LagLeadAnalyticFunctions.php