0
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) as total,但它给了我一些奇怪的输出,它添加了 N 个元素 N 次。

4

3 回答 3

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
于 2013-07-18T01:40:51.827 回答
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
于 2013-07-18T01:53:40.360 回答
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,正如查询的其余部分所使用的那样。

于 2013-07-18T01:56:10.570 回答