简体   繁体   中英

SQL Grab Data from most recent date

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.

On your main query you can apply CTE like below and get the desirec result:

Demo

WITH CTE1 AS
(SELECT A.*, ROW_NUMBER() OVER(PARTITION BY Packnum ORDER BY [Mail Date] DESC) RN
 FROM TABLE1 A)
 SELECT * FROM CTE1 WHERE RN = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM