-4
select * from employee

UNIT_ID  PARENT_UNIT   TOT_EMP
-------  -----------   -------
Oracle      IT           10
SAP         IT           20
IT          PST          30
HRGA        FA            5
FA          PST          12 

如何获得输出为:

IT     60
ORACLE 10
SAP    20
HRGA    5
FA     17
4

3 回答 3

4
select a.name, sum(a.tot_emp)
from
(
  select unit_id as name, sum(tot_emp) as tot_emp
  from employee
  group by unit_id
  UNION
  select parent_id as name, sum(tot_emp) as tot_emp
  from employee
  group by parent_id
) as a
where exists (select null
              from employee e
              where e.unit_id = a.name)
group by name;

但这不是一个真正的递归查询(这似乎是您需要的),它适用于您的样本,但可能不适用于真实数据(但我们不知道您的层次结构的深度)。

于 2013-01-17T12:04:09.537 回答
0

这是 Oracle 查询:

SELECT unit_id, SUM(total_emp) FROM stack_test
 GROUP BY unit_id
/
UNIT_ID    SUM(TOTAL_EMP)
--------   --------------
    SAP       50
    HRGA      15
    ORACLE    30

在您的帖子中创建表格并使用值填充它们总是一个好主意......

于 2013-01-17T13:26:24.527 回答
0

我不知道一些细节。可以在UNIT_ID 列中到次同名吗?如果没有,这是一个很好的查询:

select e1.UNIT_ID, SUM(TOT_EMP) AS TOT_EMP
from emploee e1
innner join emploee e2
on e1.UNIT_ID = E2.PARENT_UNIT 
group by e1.UNIT_ID

如果 UNIT_ID 列中的名称可以相同,请查看 Raphaël Althaus 的答案。这是很好的答案。

于 2013-01-17T12:14:28.310 回答