简体   繁体   English

根据最大日期获取一些值(两个表之间的查询)

[英]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) 项目(ItemId,名称)

ItemData(ItemDataId, ItemFK, Invoice, EntryDate) - ItemFK is the foreign key of ItemId in Items table ItemData(ItemDataId,ItemFK,发票,EntryDate) -ItemFK是Items表中ItemId的外键

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). 我想获得基于EntryDate(和名称)的最新发票。 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)? 我首先需要根据名称获取itemid,然后根据itemid但仅获取最后一个发票(因此使用max(enteydate)。如何使用innerjoin(或其他一些sql查询)来做到这一点?

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. 两者where whatevers都应相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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