P
P
piatachki2020-07-27 17:40:39
SQL
piatachki, 2020-07-27 17:40:39

How to select records with the maximum field value for a grouped parameter?

Two tables:

orders (заказы)
id            
s (статусы заказов)
id | time | status | order_id

The order is considered in the status that was added last (the time field is the maximum for the given order_id).
I cannot make a request that would receive a status at the input, and at the output orders (orders) with this status.
select max(os.time), os.orders 
  from order_statuses os 
    join orders o on os.orders = o.id 
  where os.status = 'NEW' 
  group by os.orders;

only mine returns the last time when the order had the status 'NEW', but I need orders that have 'NEW' - the last status.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Tsvetkov, 2020-07-27
@piatachki

SELECT order_id
  FROM order_statuses o
  WHERE (status = 'new')
    AND time = ( SELECT MAX(time) 
                     FROM order_statuses m 
                     WHERE (m.order_id = o.order_id))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question