[英]Oracle connect by clause
我在名為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_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不需要任何行(即,無需在CHILD_DEPT列中放入DEPT_G)
在您的示例中,您沒有指定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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.