有人可以帮我解决下面输出的SQL查询吗?该表位于输出之下。
empno sal OtherCollegueID OtherCollegueSalary
7499 1600 7844 1500
7521 1250 7876 1100
7566 2975 7698 2850
7654 1250 7876 1100
7698 2850 7782 2450
7782 2450 7499 1600
7788 3000 7566 2975
7839 5000 7788 3000
7844 1500 7934 1300
7876 1100 7900 950
7900 950 7369 800
7902 3000 7566 2975
7934 1300 7521 1250
员工表:
empno ename sal deptno
7369 SMITH 800 20
7499 ALLEN 1600 30
7521 WARD 1250 30
7566 JONES 2975 20
7654 MARTIN 1250 30
7698 BLAKE 2850 30
7782 CLARK 2450 10
7788 SCOTT 3000 20
7839 KING 5000 10
7844 TURNER 1500 30
7876 ADAMS 1100 20
7900 JAMES 950 30
7902 FORD 3000 20
7934 MILLER 1300 10
答案 0 :(得分:0)
Dept_no是您与员工的关系。 看起来它似乎要求找到该员工之后薪水最高的同一部门员工的员工ID和工资。
Select t1.emp_no, t1.sal, max(t2.sal) as other_emp_sal
into #temp
from employee t1
join employee t2 on t1.dept = t2.dept and t1.emp_id != t2.emp_id and t2.sal < t1.sal
select t1.*, t2.emp_id
from #temp t1
join employee t2 on t1.dept = t2.dept and t1.other_emp_sal = t2.emp_sal
这应该这样做。
答案 1 :(得分:0)
你需要一个窗口函数来取出OtherEmployeeId。这是我的建议:
SELECT x.empno,
x.sal,
x.OtherColleagueId,
x.OtherColleagueSalary
FROM
(SELECT e1.empno,
e1.sal,
e2.empno OtherColleagueId,
e2.sal OtherColleagueSalary,
row_number() OVER (PARTITION BY e1.empno ORDER BY e2.sal DESC) rn
FROM Employee e1
JOIN Employee e2
ON e1.deptno = e2.deptno AND e1.sal > e2.sal) x
WHERE x.rn = 1;