1、需求

       user表

SQL---MySQL数据库---试炼-LMLPHP

       temp表

SQL---MySQL数据库---试炼-LMLPHP

       user_temp_salary表

SQL---MySQL数据库---试炼-LMLPHP

    1.1  查找每个人在2018年前2个月的平均工资信息

SELECT b.`name` AS userName,c.name AS tempName,aa.avgSalary
FROM `user` b
INNER JOIN
(SELECT a.user_id,FORMAT(avg(a.salary),2) AS avgSalary
FROM user_temp_salary a
WHERE a.`month`<3 AND a.`year`=2018
GROUP BY a.user_id) aa
ON b.id=aa.user_id
INNER JOIN temp c ON b.temp_id=c.id

 执行结果:

SQL---MySQL数据库---试炼-LMLPHP

    1.2  找2018年每个部门、每个月的工资总和

SELECT aa.year,aa.month,b.name AS tempName,aa.sumSalary
FROM temp b
INNER JOIN
(SELECT a.year,a.month,a.temp_id,SUM(a.salary) AS sumSalary
FROM user_temp_salary a
WHERE a.year=2018
GROUP BY a.temp_id,a.month
ORDER BY SUM(a.salary) DESC) aa
ON b.id=aa.temp_id

 执行结果:

SQL---MySQL数据库---试炼-LMLPHP

05-28 16:36