-2

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!

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
Pradnya Alchetti
  • 165
  • 3
  • 12

1 Answers1

1

If you are using Oracle you can use Hierarchial query to solve this:

WITH CTE1 AS (SELECT a.*, LEVEL, CONNECT_BY_ROOT COMPANY AS PARENT
FROM table1 a
START WITH  parent_b IN ('A1', 'B1')
CONNECT BY NOCYCLE PRIOR  company = parent_b)
SELECT SUM(SALES), PARENT FROM CTE1 
WHERE PARENT IN ('A1', 'B1') 
GROUP BY PARENT;
Atif
  • 2,011
  • 9
  • 23