0

表格1

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

问题:找出每个部门薪水最高的人

要返回的行: CustomerID DeptName Salary

问题:找出每个部门薪水最高的人

要返回的行: CustomerID DeptName Salary

任何人都可以帮我解决如何为此编写 SQL 查询吗?

4

4 回答 4

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

您应该考虑到,如果每个部门的最高工资重复,则此查询将为每个部门返回多个结果。

于 2012-07-27T20:53:40.270 回答
0

从 SQL-Server 2005 及更高版本开始,使用CTEwithROW_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-fiddlehttp ://sqlfiddle.com/#!3/41ff1/2/0


如果您想返回多个具有相同薪水的客户,请使用@Lamak 建议RANK的而不是。ROW_NUMBER

以下是差异: http: //mangalpardeshi.blogspot.de/2008/10/difference-between-rownumber-rank-and.html

于 2012-07-27T21:00:32.723 回答
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
于 2012-07-27T22:43:21.667 回答
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 
于 2012-07-28T06:23:06.503 回答