在员工表中获得前三名的部门明智薪水?

时间:2016-11-16 05:36:37

标签: sql select join subquery

有两张桌子: - Employee表包含所有员工。

+----+-------+--------+--------------+  
| Id | Name  | Sa1ary | DepartmentId |   
+----+-------+--------+--------------+  
|  1 | Joe   |  70000 |            1 |  
|  2 | Henry |  80000 |            2 |  
|  3 | Sam   |  60000 |            2 |  
|  4 | Max   |  90000 |            3 |  
|  5 | Janet |  69000 |            4 |  
|  6 | Randy |  85000 |            1 |  
+----+-------+--------+--------------+  

部门表格如下: -

+----+------------+      
|DID |  DNAME     |   
+----+------------+  
|1   |  IT        |  
|2   |  ADMIN     |  
|3   |  HR        |  
|4   |  MARKETING |  
|5   |  SALES     |  
+----+------------+   

输出应该是: -

+-----+--------+--------+------+------+  
|Dname| Best    |Seond best |  Worst |  
+-----+--------+--------+------+------+  
|IT   |  40000  |30000  |10000        |  
+-----+--------+--------+------+------+    
|ADMIN| 50000   |   |50000        |   
+-----+--------+--------+------+------+  
|HR   | 70000   |60000  |60000        |   
+-----+--------+--------+------+------+  

我们必须考虑每个部门的最高,第二最高和3最高工资。

3 个答案:

答案 0 :(得分:0)

save

答案 1 :(得分:0)

在SQL Server上,您可以使用SQL Row_Number function with Partition By子句根据基于所选列的组中的值对行进行排名

我还使用了CTE表达式和GROUP By运算符

;with cte as (
select 
    Dname, Sa1ary, ROW_NUMBER() Over (Partition By d.DId Order By Sa1ary desc) rn
from employee e
inner join department d on e.DepartmentId = d.DId
)
select
    dname,
    max(Best) Best,
    max(Seond) Seond,
    max("Best Worst") "Best Worst"
from (
select
    Dname,
    case when rn = 1 then Sa1ary else null end as Best,
    case when rn = 2 then Sa1ary else null end as Seond,
    case when rn = 3 then Sa1ary else null end as "Best Worst"
from cte
) t
group by dname

请注意,结果并非如您所示,我猜错了。

enter image description here 请测试以上内容,希望有所帮助,

答案 2 :(得分:0)

尝试以下数据透视查询。

            select * from 
            (
            select DName,salary,Class from
            (
            select 
            *,
            case when RID='1' then 'Best'
            when RID='2' then 'second'
            when RID='3' then 'Best Worst'
            else
            NULL
            end as CLASS
            from (
            select DID,Dname,salary ,     
            ROW_NUMBER() OVER ( PARTITION  BY Dname ,DID
            ORDER BY salary DESC  ) as RID
             from
             #Employee E inner join  #Department D on E.DepartmentId=d.DID
             )a
            where rid <4
            )b   
            ) as x
            pivot(
            max(salary) for class in ( [Best],[Second],[Best Worst]) 
            )
            as pivot1