Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select only latest entries with IN clause?

I have a table with orders, with reoccuring order numbers per year:

create table orders (
    order_number varchar(6) NOT NULL,
    order_year year NOT NULL,
    ...
    primary key (order_number, order_year)
);

Data:

A111,2023,...
A111,2020,...
A222,2021,...

Now I want to select from a bunch of orders, but only take the ones with most recent order_year. But how?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The following query would of course select all orders from every year. How could I sort out everything but the latest year?

SELECT * FROM orders WHERE order_number IN ('A111', 'A222', ...);

>Solution :

You can use a query like this (demo):

SELECT orders.* 
FROM orders INNER JOIN (
  SELECT order_number, MAX(order_year) order_year 
  FROM orders 
  GROUP BY order_number
) x ON orders.order_number = x.order_number AND orders.order_year = x.order_year
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading