MS SQL Server:选择每月最高工资的员工详细信息

MS SQL Server:选择每月最高工资的员工详细信息,sql,sql-server,Sql,Sql Server,如何查询公司当月最高工资员工明细 尝试下面的方法。正确的查询方式是什么 Table Name: EMPLOYEE_MASTER +-------------+----------------+----------------+--------+-----------------+ | Employee_Id | Employee_Name | Designation | Age | Date_of_Joining | +-------------+----------------

如何查询公司当月最高工资员工明细

尝试下面的方法。正确的查询方式是什么

Table Name: EMPLOYEE_MASTER

+-------------+----------------+----------------+--------+-----------------+
| Employee_Id | Employee_Name  |  Designation   |  Age   | Date_of_Joining |
+-------------+----------------+----------------+--------+-----------------+
| EM07126     |     Johnson    |     Manager    |     39 | 12-May-2009     |
| EM08934     |     Raj Kumar  | Consultant     |     32 | 8-Mar-2010      |
| EM08959     |     Ganesh     |     Consultant |     30 | 20-Sep-2011     |
| EM09235     |     Santosh    |     Trainee    |     23 | 18-Jan-2012     |
| EM09423     |     Rajesh     |     Trainee    |     22 | 15-Jun-2012     |
| EM10245     |     Siva Kumar | Trainee        |     22 | 22-Aug-2012     |
+-------------+----------------+----------------+--------+-----------------+

Table Name: EMPLOYEE_DETAIL

+-------------+-------------+-----------+
| Employee_Id |    Date     |  Salary   |
+-------------+-------------+-----------+
| EM07126     | 04-Jun-2013 | 24,500.00 |
| EM07126     | 04-Jul-2013 | 25,000.00 |
| EM08934     | 03-Jun-2013 | 15,000.00 |
| EM08934     | 03-Jul-2013 | 15,100.00 |
| EM08959     | 02-Jun-2013 | 14,000.00 |
| EM08959     | 02-Jul-2013 | 14,100.00 |
| EM09235     | 01-Jun-2013 | 10,500.00 |
| EM09235     | 01-Jul-2013 | 10,500.00 |
| EM09423     | 01-Jun-2013 | 8,500.00  |
| EM09423     | 01-Jul-2013 | 8,500.00  |
| EM10245     | 01-Jun-2013 | 8,500.00  |
| EM10245     | 01-Jul-2013 | 8,500.00  |
+-------------+-------------+-----------+

一种方法使用窗口函数:

Select e.* from EMPLOYEE_MASTER e inner join (
    Select Employee_ID, Max(salary) as maxsal from EMPLOYEE_DETAIL group by Month(date)) s
WHERE e.Employee_ID=s.Employee_ID

编辑您的问题并显示您想要的结果。
select em.*, ed.yyyy, ed.mm, ed.total_salary
from employee_master em join
     (select ed.employee_id, year(date) as yyyy, month(date) as mm,
             sum(salary) as total_salary,
             rank() over (partition by year(date), month(date) order by sum(salary) desc) as seqnum
      from employee_detail ed
      group by ed.employee_id, year(date), month(date)
     ) ed
     on ed.employee_id = em.employee_id and ed.seqnum = 1;