Skip to content
Advertisement

Getting wrong sum when using group by with inner join

With reference to this question (How to get the sum in a joined table when using group by – getting wrong results) I have two tables orders and order_items. I need to group the results by days. But I also need to get the sum of energy_used for each day from another table. When I try that using a join, I get wrong order_sum for each day (they are not being summed up). Not sure what I am doing wrong.

I would like to get for each day

  • the sum of order_items.energy_used for all orders created that day
  • the sum of orders.order_sum for all orders created that day
  • the created_at and order_sum that correspond to the latest order created on that day

Here is my orders table

And here is my order_items table

And this is the desired result that I am trying to achieve

And here is the query that I have tried but I’m getting wrong results, the order_sum is not being calculated correctly. It is showing the same as last_order_sum

Here is a fiddle: https://dbfiddle.uk/?rdbms=mysql_5.6&fiddle=92b8cc2920ad9f7a7cdd56bded5a3bf2

Advertisement

Answer

Always join tables together on their relationships (in this case orders.id with order_items.order_id) and then group. to avoid duplicating order_sums for multiple order_items when joining, first group order_items by order_id.

from this point onwards you can do a join again on orders with max(o.created_at) to get the order_sum of the last order. moral of the story: keep an eye on your granularity.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement