我的桌子看起来像这样:
EmpID Salary
1 20
2 5
3 10
4 12
5 4
6 6
我想为每个EmpID计算分配的工资和最低工资之间的差异以及这个工资和最高工资之间的差异。像这样:
Min(Salary) = 4
Max(Salary) = 20
所以我的输出应该是这样的:
EmpID Salary Diff1 Diff2
1 20 16 0
2 5 1 -15
3 10 6 -10
4 12 8 -8
5 4 0 -16
6 6 2 -12
我尝试以两种方式做到这一点,但不知道下一步该做什么。
我的剧本:
SELECT EmpID, Salary,
Salary - MIN(Salary) AS Diff1,
Salary - MAX(Salary) AS Diff2
from MyTable
group by EmpID, Salary
第二种方法:
SELECT EmpID, Salary,
Salary - MIN(Salary) OVER(PARTITION BY EmpID ORDER BY salary) AS Diff1,
Salary - MAX(Salary) OVER(PARTITION BY EmpID ORDER BY salary) AS Diff2
from MyTable
group by EmpID, Salary
但它不起作用。我做错了什么。
答案 0 :(得分:4)
在group by
条款中Partition by
和order by
还从查询中移除Over
SELECT EmpID, Salary,
Salary - MIN(Salary) OVER() AS Diff1,
Salary - MAX(Salary) OVER() AS Diff2
from MyTable
或其他方式是使用效率较低的Sub-Query
SELECT EmpID, Salary,
Salary - (select MIN(Salary) from MyTable) AS Diff1,
Salary - (select MAX(Salary) from MyTable) AS Diff2
from MyTable