Employee 表保存了一年内的薪水信息,请你编写 SQL 语句,对于每个员工,查询他除最近一个月(即最大月)之外,剩下每个月的近三个月的累计薪水(不足三个月也要计算),结果请按 Id 升序,然后按 Month 降序显示。 建表语句: drop table Employee; Create table If Not Exists Employee (id int, month int, salary int); Truncate table Employee; insert into Employee (id, month, salary) values ('1', '1', '20'); insert into Employee (id, month, salary) values ('2', '1', '20'); insert into Employee (id, month, salary) values ('1', '2', '30'); insert into Employee (id, month, salary) values ('2', '2', '30'); insert into Employee (id, month, salary) values ('3', '2', '40'); insert into Employee (id, month, salary) values ('1', '3', '40'); insert into Employee (id, month, salary) values ('3', '3', '60'); insert into Employee (id, month, salary) values ('1', '4', '60'); insert into Employee (id, month, salary) values ('3', '4', '70'); insert into Employee (id, month, salary) values ('1', '7', '90'); insert into Employee (id, month, salary) values ('1', '8', '90');
时间: 2023-08-20 09:56:56 浏览: 106
请使用以下 SQL 语句来查询每个员工除最近一个月之外的近三个月的累计薪水:
```sql
SELECT e.id, e.month, SUM(e.salary) AS cumulative_salary
FROM Employee e
WHERE (e.id, e.month) NOT IN (
SELECT id, MAX(month)
FROM Employee
GROUP BY id
)
AND e.month >= (
SELECT MAX(month) - INTERVAL 3 MONTH
FROM Employee
)
GROUP BY e.id, e.month
ORDER BY e.id ASC, e.month DESC;
```
运行以上 SQL 语句后,将按照员工的 Id 升序和 Month 降序显示结果。
阅读全文