Skip to content
Advertisement

Getting unknown column in on clause when trying to get the latest record

I have two tables orders and order_items I am trying to get the last order_sum for each day using an inner join but I am running into an error in my second join.

Unknown column ‘o.last_order_date’ in ‘on clause

Here is my query

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

And here is the result I would like to get

+---------------+-----------------+-------------------+---------------------+----------------+
| date_of_month | total_order_sum | total_energy_used | last_order_date     | last_order_sum |
+---------------+-----------------+-------------------+---------------------+----------------+
| 2020-01-25    | 35.13           | 164               | 2020-01-25 15:23:00 | 10.00          |
| 2020-01-26    | 64.00           | 1                 | 2020-01-26 19:14:00 | 50.00          |
| 2020-01-27    | 35.00           | 5                 | 2020-01-27 11:13:00 | 35.00          |
+---------------+-----------------+-------------------+---------------------+----------------+

Here is a fiddle with schema http://sqlfiddle.com/#!9/bf799d/6

Advertisement

Answer

You already asked this in your previous question you were nearly there with the second inner join

select 
    date(o.created_at) date_of_month,
    sum(order_sum) as total_order_sum,
    sum(i.total_energy_used) total_energy_used,
    max(o.created_at) lastorderdate,
    max(s.last_order_sum) last_order_sum
from orders o
inner join (
    select order_id, sum(energy_used) total_energy_used
    from order_items i
    group by order_id
) i on o.id = i.order_id
join
(select order_sum last_order_sum,created_at
    from orders o
    where created_at = (select max(created_at) from orders o1 where date(o1.created_at) = date(o.created_at))
) s on date(s.created_at) = date(o.created_at) 
group by date(o.created_at);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement