2016-01-22 71 views
0

有人可以幫助我的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 

Employee表:

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 
+1

你有自己的一些SQL嗎? –

+0

不,我不知道。我在Access中嘗試,因爲我對SQL相當陌生,在面試中這個問題被問到了我,我無法回答。 –

+0

第一名員工(empno)和同事(OtherCollegueID)之間的關係是什麼?除非同事之間的聯繫是隨機的或者其他的,否則也必須有一個同事(或某些類似的)才能工作。它不能簡單地以deptno爲基礎,因爲在每種情況下都有兩個以上的員工具有相同的deptno。 –

回答

0

DEPT_NO是你的領帶員工。 它看起來是要求在該員工之後找到同一部門中具有最高工資的員工的員工編號和工資。

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 

這應該這樣做。

+0

謝謝你的答案。不幸的是它沒有奏效。我試圖通過所需的修改來訪問ms訪問權限。也許我的修改弄亂了它。 –

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; 
+0

如果沒有OtherEmployeeId,您可以使用MAX(e2.sal)而不是窗口函數並跳過外部SELECT。 –