Reputation: 495
I'm attempting to write a query that will grab the most recent retail from the most recent date. My data from the inner query looks like this:
Packnum Mail Date Retail
600002 2018-07-01 20.99
600002 2020-09-20 24.99
600003 2020-01-06 31.99
600003 2019-01-01 26.99
I'm trying to get the highest mail date and the retail that goes with it. For example I want to only see:
Packnum Mail Date Retail
600002 2020-09-20 24.99
600003 2020-01-06 31.99
My current code is as follows: (I know I have sloppy coding I'm still learning and no expert)
SELECT
a.packnum
,r.Retail as [Current Retail]
,MAX(b.firstreleasemailed) as Maildate
FROM pic704current a JOIN CatCov b on (a.CatID = b.Offer) and (a.Year = b.MailYear)
JOIN
(SELECT DISTINCT a.packnum ,max(b.FirstReleaseMailed) as Maildate ,a.RetOne as Retail
FROM PIC704Current a JOIN CatCov b on (a.CatID = b.Offer) and (a.Year = b.MailYear)
WHERE
b.firstreleasemailed <= getdate()
GROUP BY a.PackNum, a.RetOne
)r
ON a.RetOne = r.Retail
WHERE
(a.DiscountReasonCode Not in ('LT','UP', 'OR', 'ER', 'IP'))
and b.firstreleasemailed <= getdate()
GROUP BY a.packnum ,r.Retail
order by PackNum
Any help would be greatly appreciated.
Upvotes: 2
Views: 73