We have a master table for Receipts which has
RCPSEQ, RCPNUMBER, PONUMBER, VENDORNUM, DATERCPT
AND Detail table which has:
RCPSEQ, PONUMBER, ITEM
I want to write a query to pick the Item number and the VendorNum who recently sold us that Item. Problem is grouping. with below query I am getting multiple PONUMBEr for same item and date.
SELECT
p1.PONUMBER,
P2.ITEMNO,
(P2.MxDTAR) AS DATEM
FROM
dbo.PORCPL P1
join (select ITEMNO, max(DTARRIVAL)as MxDTAR from PORCPL group by ITEMNO) as P2
on P1.ITEMNO=p2.ITEMNO
order by
ITEMNO
Best Answer
You can use ROW_NUMBER() function to rank each item by it's date, being 1 the most recent one.
Or using
GROUP BY
you should join by both the item number and the date, but if you have 2 max dates with the same item you will see both.