我有3张桌子。用户,PC,部门 用户具有DepartmentID和PCID列,其中包含Departments中的ID和用户中的PCID。
我需要从用户拥有最高工资总额的部门中选择pc.id
我对这个问题做了一些尝试。
WITH cte AS (select s.did, max(Sum_Salary) as Sum_Salary from (select d.ID as did ,sum(u.Salary) as Sum_Salary from dbo.users u
inner join Departments d on u.DepartmentID=d.id
group by d.ID ) s group by s.did), cte2 as (select cte.did, cte.Sum_Salary as maxx from cte where Sum_Salary=(select max(Sum_Salary) from cte))
select cte2.did,cte2.maxx,pc.id as pc_id from cte2
inner join users u on cte2.did=u.DepartmentID
inner join PC on u.PCID=PC.id
;
有效。我对更有效的算法感兴趣。
答案 0 :(得分:1)
根据你的描述,我使用了两个ctes:第一个用于计算每个组合(部门,用户)的工资总和,第二个用于查找第一个cte中工资的最大总和。然后我加入了两个cte,只挑选那些最高工资额的PCID。
WITH cte AS (
SELECT d.id, u.PCID, SUM(u.Salary) AS Sum_Salary
FROM users u JOIN Departments d ON u.DepartmentID = d.id
GROUP BY d.id, u.PCID
), cte1 AS (
SELECT cte.id AS DeptID, MAX(Sum_Salary) AS Max_Sum_Salary
FROM cte
GROUP BY cte.id)
SELECT cte1.DeptID, cte.PCID, d.name
FROM cte
JOIN cte1 ON cte1.DeptID = cte.id AND cte.Sum_Salary=cte1.Max_Sum_Salary
JOIN Departments d ON d.id = cte1.DeptID
答案 1 :(得分:1)
您可以在部门内对薪水进行排序,可以返回第一个用户
SELECT * FROM (
select d.Name as dname,ROW_NUMBER()OVER(PARTITION BY u.DepartmentID ORDER BY u.Salary desc) AS SeqNO
FROM dbo.users u
inner join Departments d on u.DepartmentID=d.id
inner join PC on u.PCID=PC.id
where u.salary>500
) AS t WHERE t.SeqNO=1