我的 sql Group By case 在特定年份获得最高薪员工

My sql Group By case for getting highest paid employee in specific year

有两个table 1名员工 2 工资

Employee : eId, ename, salaryId
Salary : salaryId, eId, salary, date

salary table包含员工月薪记录, 喜欢:

身份证日期工资

1       2015-jan-01    10000
1       2015-feb-01    10000
1       2015-mar-01    10000
1       2014-jan-01    10000
1       2014-feb-01    10000
1       2014-mar-01    10000
2       2015-jan-01    10000
2       2015-feb-01    10000
2       2015-mar-01    10000
2       2014-jan-01    10000
2       2014-feb-01    10000
2       2014-mar-01    20000

所以查询是给我特定年份的最高薪员工,例如:2014

所以这里使用 group by 日期和薪水输出总和是:
empid - empname - sum(salary)
2 - xyz - 40000

用这样的东西试试...我只是瞥了一眼给你指明了正确的方向,这个查询可能需要一些修正

Select TOP 1 emp.eid, emp.ename, sal.salary
from Employee emp 
join Salary sal on emp.salaryID = sal.salaryID
where DATEPART(yy,sal.date) =  2014
order by sal.salary desc

祝你好运

类似这样的方法可行

with salaries as (
select to_char(date,'yyyy') y, eld, sum(salary) s_sal
from salary
group by to_char(date,'yyyy'), eld)

select eld
from salaries s
where s_sal = (select max(s_sal) from salaries where y=s.y)
and s.y='2014';

但是你没有指定DB,所以有Oracle语法。 我没有加入 Employee table,但相信添加它并不难。

MySQL代码,

SELECT Top 1 E.ename         EmployeeName,
       MAX(salary)  AS EmployeeSalary
FROM   Employee E
       INNER JOIN Salary S
            ON  E.salaryID = S.salaryID
WHERE  YEAR(S.Date) = 2014
GROUP BY
       E.eId,
       E.ename

如果要求是获取每年收入最高的员工名单,那么这可以通过 "Ranking" 逻辑来实现。

像这样:

SELECT 
    Year(SalaryMonthDate) AS [Payroll Year],
    EID, 
    Sum(Amout) AS [Annual Salary],
    RANK() OVER(PARTITION BY Year(SalaryMonthDate) ORDER BY Sum(Amout) DESC) [Rank]
FROM tblSalary
GROUP BY Year(SalaryMonthDate), EID

希望对您有所帮助。

#highest paid emp in specific year SELECT e.empId,e.empName,SUM(s.salary),s.salDate FROM emp e INNER JOIN salary s ON e.empId = s.empId WHERE YEAR(s.salDate)=2009 GROUP BY s.empId ORDER BY SUM(s.salary) DESC LIMIT 1;