I'm having issues trying to figure out how to group and sum subitem with parent item rows.
I have a SQL query that looks like this:
select
topics.name,
sum(commission_amount) as commission
from orders
left join topics
on topics.id = orders.topic_id
group by 1
This works, however I'm trying to group and use only parent topic names.
Topics table:
| id | name | topic_id |
|---|---|---|
| 1 | Meal Delivery | NULL |
| 2 | Vegan Meal Delivery | 1 |
| 3 | Vegetarian Meal Delivery | 1 |
| 4 | Mattresses | NULL |
| 5 | Hybrid Mattress | 4 |
| 6 | Memory Foam Mattress | 4 |
So a parent topic is when topic_id = NULL
Orders table:
| id | topic_id | commission_amount |
|---|---|---|
| 1 | 1 | 10 |
| 2 | 2 | 20 |
| 3 | 3 | 30 |
| 4 | 4 | 40 |
| 5 | 5 | 50 |
| 6 | 6 | 60 |
Desired output is this:
| name | commission |
|---|---|
| Meal Delivery | 60 |
| Mattresses | 150 |