r/learnSQL • u/Spendocrat • Apr 16 '26
select row with most-recent date for each ID
I have two tables, Table1 has a list of medication orders, and Table2 has a list of transactions related to the orders in Table1 (one-to-many relationship).
Is there a way to use a single SQL query to select only the most-recent transaction row from the transaction table for each row in the medication orders table?
Table2 has columns: transaction_id, order_id (foreign key to Table1), t_date, t_time, etc. to represent transactions related to the medication orders in Table1.
Hopefully that's clear. I can't wrap my head around using max() in this way.
6
u/RevolutionaryRush717 Apr 16 '26
It seems the window function
ROW_NUMBER, as inseems to be a popular approach.
1
u/Spendocrat Apr 16 '26
Thank you all for the helpful information!
1
u/Humble_Elk_4044 Apr 16 '26
SELECT t1.*, t2.*
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.order_id = t2.order_id
INNER JOIN (
SELECT order_id, MAX(t_date) AS max_date
FROM Table2
GROUP BY order_id
) latest ON t2.order_id = latest.order_id
AND t2.t_date = latest.max_date;
2
u/zdanev Apr 17 '26
if you are using googlesql/bigquery, check out the docs for max_by, or any_value/having.