Oracle connect by clause

时间:2018-03-22 05:21:31

标签: sql oracle connect-by

我在名为EXPENSE的表中提供了以下数据:

Account DEPT EXPENSE_AMT
------------------------
1001 DEPT_A 50000
1002 DEPT_B 100000
1003 DEPT_C 10000000
1004 DEPT_D 500000
1005 DEPT_E 1000

这些部门由PARENT部门控制。表名称为PARENT_CHILD

CHILD_DEPT PARENT_DEPT
----------------------
DEPT_A DEPT_E
DEPT_B DEPT_E
DEPT_C DEPT_F
DEPT_D DEPT_F
DEPT_E DEPT_G
DEPT_F DEPT_G

我需要使用Oracle connect by子句进行Oracle SQL查询,该子句生成如下输出:

CHILD_DEPT PARENT_DEPT DIRECT_FLAG TOTAL_EXPENSE
------------------------------------------------
DEPT_A DEPT_E Y 50000
DEPT_B DEPT_E Y 100000
DEPT_E DEPT_G N 150000
DEPT_C DEPT_F Y 10000000
DEPT_D DEPT_F Y 500000
DEPT_F DEPT_G N 10500000
DEPT_E DEPT_G Y 1000

顶级父DEPT_G不需要行(即不需要将DEPT_G放在CHILD_DEPT列中)

1 个答案:

答案 0 :(得分:0)

在您的示例中,您未指定DIRECT_FLAG列的位置,因为它很重要且必须位于GROUP BY子句中。

我假设该列位于EXPENSE表中。

<强>查询

SELECT 
    CHILD_DEPT, PARENT_DEPT, DIRECT_FLAG, sum(EXPENSE_AMT) TOTAL_EXPENSE
FROM 
    PARENT_CHILD, EXPENSE
WHERE
    DEPT = CHILD_DEPT
GROUP BY CHILD_DEPT, PARENT_DEPT, DIRECT_FLAG;

示例

WITH 
    EXPENSE AS (
        select 1001 as Account, 'DEPT_A' as DEPT ,50000 as EXPENSE_AMT, 'Y' DIRECT_FLAG  from dual
        union all select 1002 ,'DEPT_B',100000, 'Y'  from dual
        union all select 1003 ,'DEPT_C',10000000, 'Y'  from dual
        union all select 1004 ,'DEPT_D',500000, 'Y'  from dual
        union all select 1005 ,'DEPT_E',1000, 'Y'  from dual
        union all select 1005 ,'DEPT_E',50000 , 'N' from dual
        union all select 1005 ,'DEPT_E',50000, 'N'  from dual
        union all select 1005 ,'DEPT_E',50000, 'N'  from dual
        union all select 1033 ,'DEPT_F',10000000, 'N' from dual
        union all select 1033 ,'DEPT_F',500000, 'N'  from dual),
    PARENT_CHILD AS (
        select 'DEPT_A' as CHILD_DEPT,'DEPT_E' as PARENT_DEPT from dual
        union all select 'DEPT_B','DEPT_E'  from dual
        union all select 'DEPT_C','DEPT_F'  from dual
        union all select 'DEPT_D','DEPT_F'  from dual
        union all select 'DEPT_E','DEPT_G'  from dual
        union all select 'DEPT_F','DEPT_G'  from dual
    )
SELECT 
    CHILD_DEPT, PARENT_DEPT, DIRECT_FLAG, sum(EXPENSE_AMT) TOTAL_EXPENSE
FROM 
    PARENT_CHILD, EXPENSE
WHERE
    DEPT = CHILD_DEPT
GROUP BY CHILD_DEPT, PARENT_DEPT, DIRECT_FLAG;