2012-07-27 147 views
0

表1SQL查詢來獲取結果

CutomerID Salary 
1    2000    
2    3000    
3    4000  
4    6000  
5    5220 

表2

DeptID DeptNam 
    1  IT       
    2  Finance     
    3  Marketing 

表3

CustomerID DeptID 
    1   1 
    2   1 
    3   2 
    4   3 
    5   3 

問:找到人的智慧的H各部門薪水最高

返回行:CustomerID DeptName Salary

問:找到人最高年薪在每個部門

返回行:CustomerID DeptName Salary

任何人可以幫助我如何爲此寫入SQL查詢?

+4

氣味功課。我錯了嗎? – Steve 2012-07-27 20:49:33

+0

對不起只有SQL ...我只是盡我最大的努力學習像這樣得到不同asnwers .. – user957178 2012-07-27 20:51:29

+0

請提供一個[sqlfiddle](http://sqlfiddle.com)的例子, – 2012-07-27 20:52:43

回答

1

對於SQL Server 2005+:

;WITH CTE AS 
(
    SELECT T1.*, T3.DeptID, RANK() OVER(PARTITION BY T3.DeptID ORDER BY T1.Salary DESC) RN 
    FROM Table1 AS T1 
    INNER JOIN Table3 AS T3 
    ON T1.CustomerId = T3.CustomerId 
) 
SELECT A.CustomerId, B.DeptName, A.Salary 
FROM CTE A 
INNER JOIN Table2 B 
ON A.DeptID = B.DeptID 
WHERE RN = 1 

你應該考慮到,如果每個部門的最高薪水是重複的,那麼這個查詢將返回每個部門不止一個結果。

0

從SQL-Server 2005和超越,使用CTEROW_NUMBER功能:

查找與薪水最高的人在各部門

WITH CTE AS 
(
    SELECT t1.CustomerID ,t2.DeptName, t1.Salary , SalaryRank = 
     ROW_NUMBER()OVER(PARTITION BY t2.DeptID ORDER BY t1.Salary DESC) 
    FROM Table1 t1 
    INNER JOIN Table3 t3 ON t1.CustomerID=t3.CustomerID 
    INNER JOIN Table2 t2 ON t3.DeptID=t2.DeptID 
) 
SELECT CustomerID, DeptName, Salary FROM CTE 
WHERE SalaryRank = 1 

這裏的SQL-小提琴http://sqlfiddle.com/#!3/41ff1/2/0


如果你想要返回多個客戶,如果他們有如同@Lamak建議的那樣,使用RANK而不是ROW_NUMBER

差別如下:http://mangalpardeshi.blogspot.de/2008/10/difference-between-rownumber-rank-and.html

0
SELECT a.customerid, 
     c.deptnam, 
     a.salary 
FROM table1 a 
JOIN table3 b ON a.customerid = b.customerid 
JOIN table2 c ON b.deptid = c.deptid 
JOIN 
(
    SELECT aa.deptid, MAX(bb.salary) AS maxsalary 
    FROM  table3 aa 
    JOIN  table1 bb ON aa.customerid = bb.customerid 
    GROUP BY aa.deptid 
) d ON a.salary = d.maxsalary AND c.deptid = d.deptid 
0

試試這個:

CREATE TABLE cust(CutomerID int,Salary float) 

INSERT INTO cust 
VALUES(1,2000),(2,3000),(3,4000),(4,6000),(5,5220) 

CREATE TABLE dept(DeptID int,DeptNam varchar(10)) 

INSERT INTO dept 
VALUES(1,'IT'),(2,'Finance'),(3,'Marketing') 

CREATE TABLE custDept(CustomerID int,DeptID int) 

INSERT INTO custDept 
VALUES(1,1),(2,1),(3,2),(4,3),(5,3) 

select a.CutomerID,a.DeptNam,b.sal from 

(select c.CutomerID ,d.DeptID,c.Salary,d.DeptNam from cust c inner join custDept cd on 
c.CutomerID = cd.CustomerID 
inner join dept d 
on cd.DeptID =d.DeptID) a 

inner join 
(select d.DeptID ,MAX(c.Salary) as sal from cust c inner join custDept cd on 
c.CutomerID = cd.CustomerID 
inner join dept d 
on cd.DeptID =d.DeptID 
group by d.DeptID) b 

on a.DeptID = b.DeptID and a.Salary = b.sal