I am attempting to join two tables (purchases and purchase attributes), and then group based on the join, however NULL values are generated during the join as not every entry in table A has a corresponding ‘attributes’ in table B – this then kills my ‘group by’.
My actual implementation is more complicated than this but here is a trimmed concept of what I am trying to achieve:
I have the following Tables:
purchases:
|purchase_id | products_id | qty |
| 1 | 10 | 100 |
| 2 | 11 | 100 |
| 3 | 10 | 300 |
| 4 | 12 | 50 |
purchase_attributes:
|purchase_attributes_id | purchase_id | options_id |
| 1 | 1 | 5 |
| 2 | 3 | 5 |
| 3 | 4 | 5 |
Now, my goal is to calculate the total qty of a particular product, grouping by options_id.
So, I have the following sql:
select products_id, options_id, SUM(qty)
from purchases
left join purchase_attributes using(purchase_id)
group by products_id, options_id
Which works for all cases where the purchase_id is listed in the purchase_attributes table, however for the case of purchase_id 2, which does not appear in purchase_attributes, it does not display in my result set.
Example result set:
| products_id | options_id | SUM(qty) |
| 10 | 5 | 400 |
| 12 | 5 | 50 |
However I would like to receive the following result set:
| products_id | options_id | SUM(qty) |
| 10 | 5 | 400 |
| 11 | NULL | 100 |
| 12 | 5 | 50 |
I have tried a few things, including Coalesce inside the group by and Union(ing) two select statements together, however I cannot seem to get the correct results.
Any ideas? thanks in advance.
This does produce exactly your desired results.
Please provide an example that actually demonstrates your issue.