Sample Header Ad - 728x90

Multiple Joins with Sums

0 votes
1 answer
51 views
Here is my basic schema **wbs_item** +----+-----------+-----------+ | id | name | parent_id | +----+-----------+-----------+ | 1 | Materials | | +----+-----------+-----------+ | 2 | Drywall | 1 | +----+-----------+-----------+ | 3 | Plumbing | 1 | +----+-----------+-----------+ | 4 | Labour | | +----+-----------+-----------+ | 5 | Drywall | 2 | +----+-----------+-----------+ | 6 | Plumbing | 2 | +----+-----------+-----------+ The idea here is their is a hierarchy to breakdown the costs on the budget. **budgets** - id **budget_items** +----+-----------+-------------+-------------+-------+ | id | budget_id | wbs_item_id | name | total | +----+-----------+-------------+-------------+-------+ | 1 | 1 | 2 | Sheet Goods | 1000 | +----+-----------+-------------+-------------+-------+ | 2 | 1 | 2 | Mud / Tape | 100 | +----+-----------+-------------+-------------+-------+ | 3 | 1 | 5 | Main Floor | 500 | +----+-----------+-------------+-------------+-------+ | 4 | 1 | 5 | Basement | 500 | +----+-----------+-------------+-------------+-------+ | 5 | 1 | 3 | Rough-in | 500 | +----+-----------+-------------+-------------+-------+ | 6 | 1 | 6 | Rough-in | 1000 | +----+-----------+-------------+-------------+-------+ Here is what I am try to output +---------------------------+ | Materials | +--------------------+------+ | Drywall | 1100 | +--------------------+------+ | Plumbing | 500 | +--------------------+------+ | Total (Materials): | 1600 | +--------------------+------+ | Labour | +--------------------+------+ | Drywall | 1000 | +--------------------+------+ | Plumbing | 1000 | +--------------------+------+ | Total (Labour): | 2000 | +--------------------+------+ | Grand Total: | 3600 | +--------------------+------+ This is my Rails app so I am fine nesting these lookups i.e. looping through the main wbs_items (i.e. with NULL parent_id) then looping through the children. I can't seem to figure out the JOIN and what I am sure is a nested sub select etc. I also don't know which is more efficient - to start with the budget_items or wbs_items then add the joins etc.
Asked by Dan Tappin (103 rep)
Feb 16, 2020, 12:30 AM
Last activity: Feb 17, 2020, 07:37 PM