# Write your MySQL query statement below
579. 查询员工的累计薪水
表:Employee
+-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | month | int | | salary | int | +-------------+------+ (id, month) 是该表的主键(具有唯一值的列的组合)。 表中的每一行表示 2020 年期间员工一个月的工资。
编写一个解决方案,在一个统一的表中计算出每个员工的 累计工资汇总 。
员工的 累计工资汇总 可以计算如下:
0
。返回按 id
升序排序 的结果表。如果 id
相等,请按 month
降序排序。
结果格式如下所示。
示例 1
输入: Employee table: +----+-------+--------+ | id | month | salary | +----+-------+--------+ | 1 | 1 | 20 | | 2 | 1 | 20 | | 1 | 2 | 30 | | 2 | 2 | 30 | | 3 | 2 | 40 | | 1 | 3 | 40 | | 3 | 3 | 60 | | 1 | 4 | 60 | | 3 | 4 | 70 | | 1 | 7 | 90 | | 1 | 8 | 90 | +----+-------+--------+ 输出: +----+-------+--------+ | id | month | Salary | +----+-------+--------+ | 1 | 7 | 90 | | 1 | 4 | 130 | | 1 | 3 | 90 | | 1 | 2 | 50 | | 1 | 1 | 20 | | 2 | 1 | 20 | | 3 | 3 | 100 | | 3 | 2 | 40 | +----+-------+--------+ 解释: 员工 “1” 有 5 条工资记录,不包括最近一个月的 “8”: - 第 '7' 个月为 90。 - 第 '4' 个月为 60。 - 第 '3' 个月是 40。 - 第 '2' 个月为 30。 - 第 '1' 个月为 20。 因此,该员工的累计工资汇总为: +----+-------+--------+ | id | month | salary | +----+-------+--------+ | 1 | 7 | 90 | (90 + 0 + 0) | 1 | 4 | 130 | (60 + 40 + 30) | 1 | 3 | 90 | (40 + 30 + 20) | 1 | 2 | 50 | (30 + 20 + 0) | 1 | 1 | 20 | (20 + 0 + 0) +----+-------+--------+ 请注意,'7' 月的 3 个月的总和是 90,因为他们没有在 '6' 月或 '5' 月工作。 员工 '2' 只有一个工资记录('1' 月),不包括最近的 '2' 月。 +----+-------+--------+ | id | month | salary | +----+-------+--------+ | 2 | 1 | 20 | (20 + 0 + 0) +----+-------+--------+ 员工 '3' 有两个工资记录,不包括最近一个月的 '4' 月: - 第 '3' 个月为 60 。 - 第 '2' 个月是 40。 因此,该员工的累计工资汇总为: +----+-------+--------+ | id | month | salary | +----+-------+--------+ | 3 | 3 | 100 | (60 + 40 + 0) | 3 | 2 | 40 | (40 + 0 + 0) +----+-------+--------+
原站题解
mysql 解法, 执行用时: 271 ms, 内存消耗: 0 B, 提交时间: 2023-10-16 14:48:28
select Id, AccMonth as Month, sum(Salary) as Salary from ( select a.Id as Id, a.Month as AccMonth, b.Month as Month, b.Salary as Salary from ( select Employee.Id as Id, Employee.Month as Month from Employee, (select Id, max(Month) as Month from Employee group by Id) as LastMonth where Employee.Id = LastMonth.Id and Employee.Month != LastMonth.Month) as a join Employee as b on a.Id = b.Id and a.Month - b.Month <= 2 and a.Month - b.Month >= 0 ) as acc group by Id, AccMonth order by Id, Month desc
mysql 解法, 执行用时: 331 ms, 内存消耗: 0 B, 提交时间: 2023-10-16 14:48:03
# Write your MySQL query statement below SELECT E1.id, E1.month, (IFNULL(E1.salary, 0) + IFNULL(E2.salary, 0) + IFNULL(E3.salary, 0)) AS Salary FROM (SELECT id, MAX(month) AS month FROM Employee GROUP BY id HAVING COUNT(*) > 1) AS maxmonth LEFT JOIN Employee E1 ON (maxmonth.id = E1.id AND maxmonth.month > E1.month) LEFT JOIN Employee E2 ON (E2.id = E1.id AND E2.month = E1.month - 1) LEFT JOIN Employee E3 ON (E3.id = E1.id AND E3.month = E1.month - 2) ORDER BY id ASC , month DESC ;