SELECT dep.depName, SUM(worker.salary) as total
FROM team, worker
WHERE worker.depID = dep.depID
GROUP BY dep.depID
SELECT dep.depName, SUM(manager.salary) as total
FROM manager, dep
WHERE manager.depID = dep.depID
GROUP BY team.depID
我尝试了以下几行:SELECT dep.depName,SUM(manager.salary)+ SUM(worker.salary)作为总计,但它给了我一些奇怪的输出,它添加N个元素N个时间。
答案 0 :(得分:1)
您需要执行UNION语句的子查询
SELECT dep.depName, sum(salary) as total, dep.depID
FROM
(
(SELECT dep.depName, worker.salary as salary, dep.depID
FROM team, worker
WHERE worker.depID = dep.depID
)
UNION
(SELECT dep.depName, manager.salary as salary, dep.depID
FROM manager, dep
WHERE manager.depID = dep.depID
)
) dep GROUP BY dep.depID
答案 1 :(得分:0)
这样的事情:
SELECT result.depName, SUM(worker.salary) as total, manager_total
FROM team, worker
INNER JOIN
(SELECT dep.depID as depID, dep.depName as depName, SUM(manager.salary) as manager_total
FROM dep
LEFT OUTER JOIN manager ON manager.depID = dep.depID
GROUP BY dep.depID, dep.depName) as result ON result.depID = team.depID
WHERE worker.depID = team.depID
GROUP BY result.depName, manager_total
答案 2 :(得分:0)
更有效的方法是按部门对结果求和,而不用进行连接。然后加入部门名称。
此方法还允许您将部门工资分为两组:
select depId, sum(wsalary) as wsalary, sum(msalary) as msalary,
sum(wsalary) + sum(msalary) as total
from ((select depId, sum(w.salary) as wsalary, null as msalary
from worker w
group by depId
)
union all
(select depId, NULL as wsalary, sum(m.salary) as msalary
from manager m
group by depId
)
) t join
dep d
on t.depId = d.depId
group by t.depId
我假设第一个team
子句中的from
实际上是指dep
,正如查询的其余部分所使用的那样。