I'm coming to you with a problem that's been bugging me for a while.
I have this database, Registering every sales made by a shop, the columns are such :
The product code is unique to every item (a barcode basically), and I want to extract the latest sale for each product_code provided in the query, so let's say we have "P914", "P959" and "P953" for input, the output should be :
So i've been trying two methods to achieve this result, the first with a simple max() function and group by :
select SALE_ID, max(DATE_OF_SALE) as DATE_MAX, PRODUCT_CODE, VENDOR
from SALES
where PRODUCT_CODE in ('P914', 'P953', 'P959')
and DATE_OF_SALE is not null
group by SALE_ID, VENDOR, PRODUCT_CODE order by DATE_MAX desc;
The second method i've been trying to limit the DATE_OF_SALE with a second select :
select t1.SALE_ID, t1.DATE_OF_SALE, t1.PRODUCT_CODE, t1.VENDOR
from SALES t1
where t1.PRODUCT_CODE in ('P914', 'P953', 'P959')
and t1.DATE_OF_SALE = (select max(t2.DATE_OF_SALE) from SALES t2 where t2.SALE_ID = t1.SALE_ID group by product_code)
order by d_realisation desc;
Both queries give the exact same result :
I really can't catch what I'm doing wrong, and how to do it right. If anyone could help me, I'd be most grateful
Thank you all for reading !