If you want last 2 then there is no way to get around a TOP 2
logic as that is exactly what it is doing. If you want the max date then MAX(LogDate)
gives you that. If you want the max 2 dates then you'd combine the two but note that ordering is irrelevant without an ORDER BY
clause. Without an explicit ordering column(s) then the ordering is undefined.
Note: I'm using a table variable @Table_1
. Replace with your actual table name.
This gives you the top 2 unique LogDate
values. In your sample data it would be 2021-02-14
and 2021-02-13
.
SELECT TOP 2 Max(LogDate) FROM @Table_1 GROUP BY LogDate ORDER BY LogDate DESC
If you want the top 2 rows for the max LogDate
then the query is a little different. This query gives you the top 2 rows where the rows are ordered by LogDate
descending and then by the div_id
ascending. The results here would be 495 in both cases because you have 2 rows with the same values.
SELECT TOP 2 div_id FROM @Table_1 ORDER BY LogDate DESC, div_id