表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查询吗?
答案 0 :(得分: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
您应该考虑到,如果每个部门的最高工资重复,那么此查询将为每个部门返回多个结果。
答案 1 :(得分:0)
从SQL-Server 2005及更高版本,使用带ROW_NUMBER
函数的CTE
:
找到每个部门薪水最高的人
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-fiddle :http://sqlfiddle.com/#!3/41ff1/2/0
如果您想要返回多个客户,如果他们的工资相同,请使用RANK
代替ROW_NUMBER
,如@Lamak建议的那样。
以下是差异:http://mangalpardeshi.blogspot.de/2008/10/difference-between-rownumber-rank-and.html
答案 2 :(得分: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
答案 3 :(得分: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