我有以下表格
Employee(eid, ename, deptid)
ESal(eid, salary)
EDept(deptid, dept)
是否有办法获得部门支付的总薪水,并获得在同一查询中支付的总薪水。
这样的事情:
Dept1 | 100
Dept2 | 300
Dept3 | 200
Total | 600
答案 0 :(得分:0)
我执行了以下操作来解决相同的问题
我基本上使用left join
和employee
表执行了edept
esal
表,并按工资执行了一组。为了得到总数WITH ROLLUP
,它给了我所有检索到的工资总数
mysql> select * from employee;
+-----+-------+--------+
| eid | ename | deptid |
+-----+-------+--------+
| 1 | emp1 | 1 |
| 2 | emp2 | 1 |
| 3 | emp3 | 2 |
| 4 | emp4 | 3 |
| 5 | emp5 | 3 |
| 6 | emp6 | 2 |
+-----+-------+--------+
6 rows in set (0.00 sec)
mysql> select * from edept;
+--------+-------+
| deptid | dept |
+--------+-------+
| 1 | HR |
| 2 | Admin |
| 3 | Dev |
+--------+-------+
3 rows in set (0.00 sec)
mysql> select * from esal;
+-----+--------+
| eid | salary |
+-----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 230 |
| 4 | 120 |
| 5 | 400 |
| 6 | 100 |
+-----+--------+
6 rows in set (0.00 sec)
SELECT ifnull(dept, 'Total') as 'Dept', sum( salary )
AS 'salary' FROM employee
LEFT JOIN edept ON employee.deptid = edept.deptid
LEFT JOIN esal ON employee.eid = esal.eid
GROUP BY dept
with rollup;
+-------+--------+
| Dept | salary |
+-------+--------+
| Admin | 330 |
| Dev | 520 |
| HR | 300 |
| Total | 1150 |
+-------+--------+
4 rows in set, 1 warning (0.00 sec)
答案 1 :(得分:-1)
您可以尝试使用UNION。这样的事情可能是:
(
SELECT
EDept.dept,
e.salary
FROM
EDept
JOIN (
SELECT
e.deptid,
SUM(s.salary) as salary
FROM
Employee as e
JOIN ESal as s
ON e.eid = s.eid
GROUP BY
e.deptid
) as e
ON e.deptid = EDept.deptid
)
UNION
(
SELECT
"Total",
SUM(salary)
FROM
ESal
)