[Solved] How to get the sum in a joined table when using group by – getting wrong results


I understand that you want, for each day:

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

Your sample data is not very representative of that – it has only one order per day. Also it is unclear why created_at is repeated in both tables; you should really be relying on the order_id to relate both tables

Here is a query for the above purpose: this works by joining the orders table with an aggregate query that computes the total energy per day (using order_id to get the created_at date from orders), and filters on the latest order per day:

select 
    date(o.created_at) date_of_month,
    i.total_energy_used,
    o.created_at last_order_date,
    o.order_sum last_order_sum
from orders o
inner join (
    select date(o1.created_at) date_of_month, sum(i1.energy_used) total_energy_used
    from orders o1
    inner join order_items i1 on o1.id = i1.order_id
    group by date(o1.created_at)
) i on i.date_of_month = date(o.created_at)
where o.created_at = (
    select max(o1.created_at)
    from orders o1
    where date(o1.created_at) = date(o.created_at)
)

Demo on DB Fiddle:

date_of_month | total_energy_used | last_order_date     | last_order_sum
:------------ | ----------------: | :------------------ | -------------:
2020-01-25    |                77 | 2020-01-25 09:13:00 |          25.13
2020-01-26    |                75 | 2020-01-26 10:14:00 |          14.00
2020-01-27    |                 0 | 2020-01-27 11:13:00 |          35.00

4

solved How to get the sum in a joined table when using group by – getting wrong results