簡體   English   中英

具有累積計數的Oracle分層SQL

[英]Oracle hierarchical sql with rollup count

我將如何在Oracle中編寫SQL以返回具有匯總計數的樹視圖:

SQL將返回以下內容:

KLAS - COUNT

----------------------------------------------

ROOT - 10

   KLAS1 - 5

       KLAS2 - 2

       KLAS3 - 3

  KLAS4 - 5

       KLAS5 - 5

  KLAS6 - 0

       KLAS7 - 0

我有兩個表,一個是結構保留的位置,第二個是數據存儲的位置。 兩個表都由klas coumn連接

復制表的代碼:

create table table1 (id number, parent_id number, klas varchar2(10));  
insert into table1 (id, parent_id, klas) values (1, null, 'ROOT');  
insert into table1 (id, parent_id, klas) values (2, 1, 'KLAS1');  
insert into table1 (id, parent_id, klas) values (3, 2, 'KLAS2');  
insert into table1 (id, parent_id, klas) values (4, 2, 'KLAS3');  
insert into table1 (id, parent_id, klas) values (5, 1, 'KLAS4');  
insert into table1 (id, parent_id, klas) values (6, 5, 'KLAS5');  
insert into table1 (id, parent_id, klas) values (7, 1, 'KLAS6');  
insert into table1 (id, parent_id, klas) values (8, 7, 'KLAS7');  



create table table2 (klas varchar2(10), cnt number);  
insert into table2(klas, cnt) values ('KLAS2', 2);  
insert into table2(klas, cnt) values ('KLAS3', 3);  
insert into table2(klas, cnt) values ('KLAS5', 5);  

commit;  

問候,伊戈爾

with c1 (parent_id, id, klas, p, o) as
(
  select 
     parent_id, id, klas, '' as p, lpad(id, 10, '0') as o
     from table1
     where parent_id is null
  union all
  select 
     table1.parent_id, table1.id, table1.klas, 
     c1.p || '.....',
     c1.o || '.' || lpad(table1.id, 10, '0') as o
     from table1
     inner join c1 on table1.parent_id = c1.id
),
c2 (id, klas, p, o, cnt) as
(
  select c1.id, c1.klas, c1.p, c1.o, nvl(table2.cnt, 0)
  from c1
  left outer join table2 on c1.klas = table2.klas
)
select c3.p || c3.klas, (select sum(cnt) from c2 where c2.o like c3.o || '%') from c2 c3
order by c3.o

SQLFiddle- http: //sqlfiddle.com/#!4/be779/97

說明

第一個CTE用於定位(即......)和排序(這是通過構造列o來完成的,以確保子代位於父代之下(因此,如果父代o是xxxx,則子代將是xxxx ||)

第二個CTE剛獲得cnts-我想您可以在第一個CTE本身中做到這一點,但這很難理解。

最終查詢中的子查詢僅獲得一個節點及其子節點之和。

范圍

  1. 請注意,您可以在此ID上最多輸入10個數字ID,如果要翻閱,則必須在lpad上更改10。
  2. 深度限制取決於varchar(max)-您為每個級別添加11個字符(10 +一個。)。 如果您願意限制自己的ID長度,則可以增加深度限制(一個5位數長的ID只會為每個級別添加6個字符)。
  3. 對於o,您實際上不需要。,但是它有助於了解發生了什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM