algorithm - Finding recursive sum in SQL statement -


i've 2 tables , b like: a (id, dep_id) , b (id, amount)

the data in tables this

a                 b  id  dep_id        id   amount --- -------       ---- -------- 1   2             1    100     2   3             2    200 3   null          3    300    4   null          4    400 

the id column in table holds id table b. given id in table a, there might dep_id holds id of table b.

the requirement calculate sum of amount of entry in b , of dependent entries. has done in 1 single sql query. can't use pl/sql block that. idea how that.

example:

sum(id=1) = 100(id=1,dep_id=2) + 200(id=2,dep_id=3) + 300(id=3) = 600 

you can use connect root build link of dependency (hierarchical query), aggregate:

sql> select id, sum(amount)   2    (select connect_by_root(a.id) id, b.amount   3              4            join b on a.id = b.id   5           start a.id = 1   6           connect prior a.dep_id = a.id)   7   group id;          id sum(amount) ---------- -----------          1         600 

additional solutions available on similar more complex schema (for example id:1 needs 4xid:2, needs 8xid:3 each) on this sql quiz on plsqlchallenge.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -