赞
踩
困难
Employee 表保存了一年内的薪水信息。
请你编写 SQL 语句,来查询每个员工每个月最近三个月的累计薪水(不包括当前统计月,不足三个月也要计算)。
结果请按 ‘Id’ 升序,然后按 ‘Month’ 降序显示。
SELECT E1.Id,E1.Month,SUM(E2.Salary) as Salary
FROM Employee E1,Employee E2
WHERE E1.Id = E2.Id
AND E1.Month >= E2.Month # 防止取到比当前月大的月份
AND E1.Month < E2.Month+3 # E1的月份比E2的大,但不大于3 妙
AND (E1.Id,E1.Month) NOT IN (SELECT Id, MAX(Month) FROM Employee GROUP BY Id) #去掉本月的统计结果
GROUP BY E1.Id,E1.Month
ORDER BY E1.Id ASC, E1.Month DESC
SELECT Id,Month,Salary
FROM
(SELECT E1.Id,E1.Month,SUM(E2.Salary) AS Salary
FROM Employee E1,Employee E2
WHERE E1.Id=E2.Id
AND E1.Month <= E2.Month+2
AND E1.Month >= E2.Month
GROUP BY E1.Id,E1.Month) tmp
WHERE (Id,Month) NOT IN (SELECT Id,MAX(Month) FROM Employee GROUP BY Id)
ORDER BY Id ASC,Month DESC
外层的where筛选明明可以放进内层,却嵌套了外层结构,造成冗余与运行压力,能不用子查询就不用。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。