问题描述
我在下表中有三列(Empno,Ename,Salary)
Empno Ename Salary
101 Ashok 1000
102 Kumar 2000
103 Mani 3000
Empno Ename Salary Difference_in_Salary
101 Ashok 1000 1000
102 Kumar 2000 1000
103 Mani 3000 1000
解决方法
计算“差异”的方法有很多,因为它取决于您想要的差异:
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 | ENAME | SALARY | DIFFERENCE_FROM_AVG | DIFFERENCE_FROM_NEXT | DIFFERENCE_FROM_PREV | DIFFERENCE_FROM_MIN | DIFFERENCE_FROM_MAX ----: | :---- | -----: | ------------------: | -------------------: | -------------------: | ------------------: | ------------------: 101 | Ashok | 1000 | 1000 | 1000 | 1000 | 0 | 2000 102 | Kumar | 2000 | 0 | 1000 | 1000 | 1000 | 1000 103 | Mani | 3000 | 1000 | null | 1000 | 2000 | 0
db 提琴here