[英]How do you combine two sum queries into one?
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
I tried something along the line of: SELECT dep.depName, SUM(manager.salary)+SUM(worker.salary) as total but it gave me some strange output, it adds N elements N number of time. 我尝试了以下方法:SELECT dep.depName,总计SUM(manager.salary)+ SUM(worker.salary),但它给了我一些奇怪的输出,它增加了N个元素N次。
You need to do a subquery of a UNION statement 您需要对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
What about something like this : 那么这样的事情呢:
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
The more efficient way is to sum the results by department without doing a join. 更有效的方法是按部门汇总结果, 而不进行联接。 Then join in the department name. 然后加入部门名称。
This method also allows you to separate the department salaries into the two groups: 此方法还允许您将部门薪金分为两组:
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
I am assuming the team
in the first from
clause really refers to dep
, as used in the rest of the query. 我假设第一个from
子句中的team
确实引用了dep
,在其余的查询中都使用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.