有很多方法可以计算“差异”,因为这取决于您想要的差异:
SELECT t.*,
ABS( salary - AVG( salary ) OVER () ) AS difference_from_avg,
LEAD( salary ) OVER ( ORDER BY salary ) - salary AS difference_from_next,
salary - LAG( salary, 1, 0 ) OVER ( ORDER BY salary ) AS difference_from_prev,
salary - MIN( salary ) OVER () AS difference_from_min,
MAX( salary ) OVER () - salary AS difference_from_max
FROM table_name t
其中,对于您的示例数据:
CREATE TABLE table_name ( Empno, Ename, Salary ) AS
SELECT 101, 'Ashok', 1000 FROM DUAL UNION ALL
SELECT 102, 'Kumar', 2000 FROM DUAL UNION ALL
SELECT 103, 'Mani', 3000 FROM DUAL;
输出:
EMPNO |姓名 |工资 | DIFFERENCE_FROM_AVG | DIFFERENCE_FROM_NEXT | DIFFERENCE_FROM_PREV | DIFFERENCE_FROM_MIN | DIFFERENCE_FROM_MAX
----: | :---- | -----: | ------------------: | -------------------: | -------------------: | ------------------: | ------------------:
101 |阿肖克 | 1000 | 1000 | 1000 | 1000 | 0 | 2000
102 |库马尔 | 2000 | 0 | 1000 | 1000 | 1000 | 1000
103 |玛尼 | 3000 | 1000 | 空 | 1000 | 2000 | 0
db小提琴here