简体   繁体   中英

How to get sql result for missing tree level?

i have a tree with let's assume 14 levels but there are some gaps in tree branch like

tree values a>b>..>h>i>..>k>l>..>n
tree level:=1 2  8 9 11 12 14

need to get the result like

a>b>h>h>h>h>h>i>k>k>l>n>n>
1 2 3 4 5 6 7 8 9 10 11 12 13 14

basically i have a table with 7 records so need 14 records in single query i have primary key or tree level as specified.

agent_id,commission,lvl,amount  
a,1%,1,500  
b,1%,2,500  
h,1%,8,500  
i,1%,9,500  
k,1%,11,500  
l,1%,12,500  
n,1%,13,500  

it is a tree to table mapping and i am just giving single branch not to complicate it further.

result should be

 a (5+5+5+5+5+5+5)=35
 b (5+5+5+5+5+5+5+5+5+5+5)=55
 h (5+5+5+5+5)=25
 i (5+5+5+5+5)=25
 k (5+5+5)=15
 l (5+5+5)=15
 n 5

i need to give commission to N on 500-1% then for L on (500(n)+500(gap)+500(l))-1% but then the empty tree node M should not be considered for others commission but then again for K (500(n)+500(l)+500(k))1% and so on till agent A so for B need to consider for empty agents commission also but only for lvl 3,4,5,6,7.

SQL Fiddle

Oracle 11g R2 Schema Setup :

CREATE TABLE data ( agent_id,commission,lvl,amount ) AS
SELECT 'a',0.01, 1,500 FROM DUAL UNION ALL  
SELECT 'b',0.01, 2,500 FROM DUAL UNION ALL
SELECT 'h',0.01, 8,500 FROM DUAL UNION ALL
SELECT 'i',0.01, 9,500 FROM DUAL UNION ALL
SELECT 'k',0.01,11,500 FROM DUAL UNION ALL
SELECT 'l',0.01,12,500 FROM DUAL UNION ALL
SELECT 'n',0.01,14,500 FROM DUAL;

Query 1 :

SELECT agent_id,
       SUM( commission*amount ) OVER ( ORDER BY lvl DESC )
         + COALESCE(
             commission*amount*(LAG( lvl ) OVER ( ORDER BY lvl DESC )-lvl-1 ),
             0
           )
         AS total
FROM   data

Results :

| AGENT_ID | TOTAL |
|----------|-------|
|        n |     5 |
|        l |    15 |
|        k |    15 |
|        i |    25 |
|        h |    25 |
|        b |    55 |
|        a |    35 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM