Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Selecting newest related record in join 1

Status
Not open for further replies.

pkahlo

Programmer
Nov 3, 2003
29
US
I'm having trouble creating a query that will select the newest record in a related record. I have a table of items that have related records in the table "StockTake". StockTake contains 3 fields:

ItemID
StockTakeDate
Quantity

Basically, I want to select the record in StockTake that has the most recent StockTakeDate for each Item. The below query does this, but I also want this query to select all items that have NO records in StockTake.

This is what I have so far:

SELECT Items.*, StockTake.StockTakeDate, StockTake.Quantity
FROM Items LEFT JOIN StockTake ON Items.ItemID = StockTake.ItemID
WHERE (StockTake.StockTakeDate)=(SELECT
MAX(StockTake.StockTakeDate)
FROM
StockTake
WHERE
Items.ItemID = StockTake.ItemID)


How can I make this also select items with no records in StockTake?

Thanks!
 
Hi,

try this:

WHERE ((StockTake.StockTakeDate)IN(SELECT
MAX(StockTake.StockTakeDate)
FROM
StockTake
WHERE
Items.ItemID = StockTake.ItemID)
OR

((StockTake.StockTakeDate)NOT IN(SELECT
MAX(StockTake.StockTakeDate)
FROM
StockTake
WHERE
Items.ItemID = StockTake.ItemID)
 
I believe if you add
Code:
or StockTake.StockTakeDate is null
at the where clause you will get these records.
 
Thanks nicsin! I thought I had tried something like that already and it wasn't working.
 
Yeah you are right actually,

sorry chaps its Friday and I haven't plugged my brain in yet.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top