简体   繁体   中英

Delete rows older than Max date by given ID

I've a simple temp table created in a stored proc, consisting of an ID field (not primary key) and a date associated to each. What I want to do is keep only the ID/Date record which has the most recent Date, for each ID

I'd written the following, but it does not seem to be doing quite what I want

DELETE #summary
FROM #summary s1, #summary s2
WHERE s1.evt_dte != (
SELECT MAX(s1.evt_dte)
    FROM #summary s1, #summary s2
    WHERE s1.evt_or_cat_num = s2.evt_or_cat_num)
AND s1.evt_or_cat_num = s2.evt_or_cat_num

What I've tried to do is compare the table with itself and delete any records with the evt_dte less than the MAX for each evt_or_cat_num stored.

Any ideas how this can be tweaked to work correctly?

You could join on the data you want to keep and delete all where that link could not be made

DELETE s1
FROM #summary s1
left JOIN 
(
   select evt_or_cat_num, MAX(evt_dte) maxdt
   from #summary
   group evt_or_cat_num
) s2 on s1.evt_or_cat_num = s2.evt_or_cat_num 
    and s1.evt_dte = s2.maxdt
where s2.evt_or_cat_num is null

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