简体   繁体   中英

Get some value based on the max date (query between two tables)

I have two tables, I would like to get one value based on some max date. Here are the tables structures:

Items (ItemId, Name)

ItemData(ItemDataId, ItemFK, Invoice, EntryDate) - ItemFK is the foreign key of ItemId in Items table

What I know is the Name of the item only. I would like to get the latest Invoice based on the EntryDate (and the name). I 1st need to get the itemid based on the name, then get the invoice based on the itemid but only the last one (so using max(enteydate). How to do so with using innerjoin (or some other join sql query)?

You join to a derived table, which is a subquery with an alias.

select yourfields
from someTable join otherTablesMaybe on something
 join (
select id, max(datefield) maxDate
from someTable
where whatever
group by id ) derivedTable on someTable.id = derivedTable.id
and someTable.datefield = maxDate
where whatever

The two where whatevers should be the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM