Skip to content
Advertisement

Conditional join on soonest date – SQL Server 2017

I am working with two tables:

tblOrders

and tblPOs

I am trying to join these two tables, and for each order, select the PO with the earliest arrival date (in the event there is more than one).

So for Order Number 10244, it has two POs, PO99455 and PO99456. I would want PO99456 to be associated, since it’s date of 03/11/2020 is sooner than PO99455‘s date of 03/22/2020.

An ideal resulting dataset would look like:

Currently, I have written:

Which yields:

I’ve set up a SQL FIDDLE with this demo. How can I change my query to achieve the desired results?

Advertisement

Answer

Use OUTER APPLY:

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