Highest Salary in each department

前端 未结 30 1508
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 22:16

I have a table EmpDetails:

DeptID      EmpName   Salary
Engg        Sam       1000
Engg        Smith     2000
HR          Denis     1500
HR                  


        
30条回答
  •  花落未央
    2021-01-30 23:12

    This is the best possible solution for ORACLE:

    Select * from (select customerid, city, freight,
    row_number() over (partition by customerid order by freight desc) Row_Number from 
    (select orders.orderId, customers.CUSTOMERID, customers.city, orders.FREIGHT from orders inner join customers on orders.customerid = customers.customerid where customers.country='Germany' order by customers.customerid, orders.freight desc) 
    order by customerid, freight desc) where Row_Number<=2;
    

    Notice here I have used partition by clause for marking row number, this is majorly because we need to partition the records grouping them according to customer id. I have used two inner queries here. The inner most query is to give a view which is sorted according to customer ID and decreasing order of cost. Now from that we need to obtain always top two records so firstly we need to name them and then we need to filter them according to rownum. Second level query is to mark rownum according to customer ID. And final query will filter the result according to rownum. For every partition.

提交回复
热议问题