Question

I am having a problem figuring out how to get a particular result from my data and I can't seem to write a query that will do the trick.

Here is what I have. I have a table [Products] which contains the details of a particular product and I have a second table [ProdTrans] the two are in a one to many relationship on the Product ID number field "PrID" the ProdTrans table also has a date field for each record of when it was created and a price. the issue I am having is that I want to build a query that will take the most recent record for each PrID and return them as a list. I tried using a where clause Where Max(Date) but that seems to be only returning records with the most recent date overall and skipping some of the PrID's whose most recent record is not the most recent overall date.

I am uncertain how I should adjust my criteria to correct this issue.

here is what I have written thus far.

    Select *
    From ProdTrans
    Where transDate = Max(transDate)
    Order By PrID

I want it to basically return a list of all my PrID's on the table with the most recent transaction for the PrID in this case what the current pricing for the product is.

please help I know I am missing something simple but for the life of me can not remember what it is.

[UPDATE]

Alright so let me help clarify what I need to have as my output so below I will give an example dataset from the table

PrID CreateDate Cost Margin
001 1/1/2000 25.00 2.10 005 2/11/2005 15.48 1.50 002 3/5/2005 8.49 0.23 001 2/10/2006 22.95 1.19

and so on What I need to get is a list that returns only one instance of each PrID which must be the one with the most recent Date/Time value. also with some digging I found out that there is no foreign key relationship on the PrID field they are all manually entered (again this is a legacy system that I am trying to patch so I did not set it up nor design it. just have to work around its odd design) This procedure is being used to output this data set to an external application.

Was it helpful?

Solution

SELECT P.PRID, COST,MARGIN
FROM ProdTrans AS P
JOIN ( SELECT MAX(TRANSDATE) AS MAXDATE, PRID
FROM ProdTrans
GROUP BY PRID ) AS M
  ON M.PRID = P.PRID 
 AND M.MAXDATE = P.TRANSDATE
ORDER BY P.PRID

OTHER TIPS

try this

select * from ProdTrans 
     where
     (prid,date) IN (Select prid,max(date)
                   From ProdTrans
                   group by prid)    

for Oracle and MySQL DB

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top