I have a small SQL table as follows:
create table temp (
company varchar2(10) not null,
sales NUMBER,
parent_b VARCHAR2(10),
PRIMARY KEY (company),
CONSTRAINT company_branch_reference FOREIGN KEY (parent_b)
REFERENCES temp(company)
);
The contents of the table are as follows:
+---------+-------+----------+
| COMPANY | SALES | PARENT_B |
+---------+-------+----------+
| A1 | 20 | A1 |
| A2 | 30 | A1 |
| A3 | 30 | A1 |
| A4 | 40 | A2 |
| A5 | 10 | A2 |
| A6 | 20 | A3 |
| B1 | 40 | B1 |
| B2 | 20 | B1 |
+---------+-------+----------+
In this case, each company has a reference to the parent company. For example, A1 itself is a parent so the Parent column has A1 for A2, A3 the Parent column has A1
I want to calculate the total sales of each parent as follows:
The parent A1 has a total sale of 20+30+30+40+10+20 = 150
The parent B1 has a total sale of 40+20 = 60
The output should be as follows:
+----------+-------+
| Parent_b | Sales |
+----------+-------+
| A1 | 150 |
| B1 | 60 |
+----------+-------+
Can someone please help me out with a MySQL query for this scenario.
Thanks in advance!