简体   繁体   中英

Sql query to find sum of a column in related rows

I have two tables like

1.GROUP_TABLE

Name  Under
--------------
G1    OWNED
G2    G1
G3    G2
G4    G1
G5    G2
G6    G4
G7    G2
  1. STOCK_TABLE

     group_name stock ------------------- G1 10 G2 20 G3 30 G4 10 G5 10 G6 10 G7 20 

In grouptable there is groups belongs under another groups. if i will required stock of G1 then it will retrurn 110 (sum of all under groups related to G1). As: (G1)->(G2,G4)->(G5,G6,G7). same with G2 -80 because (G2)->(G3,G5,G7) and so on for G3,G4,G5,G6,G7.

I need result like

TillGroup           Stock
--------           --------
G1                110
G2                80
G3                30
G4                20
G5                10
G6                10
G7                20

Please suggest me any sql query witch will provide me same result Thanks in advance.

You'd use a recursive query for this:

with tree as 
(
  select name as master_name, name as descendant_name, under from group_table
  union all
  select 
    parent.name as master_name, 
    child.descendant_name as descendant_name, 
    parent.under
  from group_table parent
  join tree child on child.under = parent.name
)
select tree.master_name, sum(stock_table.stock)
from tree
join stock_table on stock_table.group_name = tree.descendant_name
group by tree.master_name
order by tree.master_name;

See SQL fiddle http://www.sqlfiddle.com/#!3/4e557/26 .

Edit: Having re-read the question more carefully, my answer will not work as it does not traverse the childrens children.

select G.NAME, SUM(G1S.STOCK) + GS.STOCK
from GROUP_TABLE G -- consider this the parent
JOIN STOCK_TABLE GS ON GS.GROUP_NAME = G.NAME -- Get its stock number
JOIN GROUP_TABLE G1 ON G1.UNDER = G.NAME -- self-join to get all its children
JOIN STOCK_TABLE G1S ON G1S.GROUP_NAME = G1.NAME -- get the stock number for each of its children
GROUP BY G.NAME, GS.STOCK

Sorry, I haven't compiled this to check the syntax. There might be some small syntax errors.

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