Home > Enterprise >  SQL Server: How to retrieve all record based on recent datetime
SQL Server: How to retrieve all record based on recent datetime

Time:11-08

First off, apologies if this has been asked elsewhere as I was unable to find any solution. The best I get is retrieving latest 1 record or 2-3 records. I'm more in search of all records (the number could be dynamic, could be 1 or 2 or maybe 50 ) based on recent Datetime value. Well so basically here is the problem,

I have a table as follows,

APILoadDatetime RowId ProjectId Value
2021-07-13 15:09:14.620 1 Proj-1 101
2021-07-13 15:09:14.620 2 Proj-2 81
2021-07-13 15:09:14.620 3 Proj-3 111
2021-07-13 15:09:14.620 4 Proj-4 125
2021-05-05 04:46:07.913 1 Proj-1 99
2021-05-05 04:46:07.913 2 Proj-2 69
2021-05-05 04:46:07.913 3 Proj-3 105
2021-05-05 04:46:07.913 4 Proj-4 115
... ... ... ...

What I am looking to do is, write up a query which will give me all the recent data based on Datetime, so in this case, I should get the following result,

APILoadDatetime RowId ProjectId Value
2021-07-13 15:09:14.620 1 Proj-1 101
2021-07-13 15:09:14.620 2 Proj-2 81
2021-07-13 15:09:14.620 3 Proj-3 111
2021-07-13 15:09:14.620 4 Proj-4 125

The RowId shows (as the name suggests) gives the number of Rows for a particular Datetime block. This will not always be 4, it's dynamic based on the data received so could be 1,2,4 or even 50 ...

Hope I was able to convey the question properly, Thank you all for reading and Pre-Thank you to those who provide solution to this.

CodePudding user response:

you can use window function row_number to find out the latest entry for each projectid:

select * from (
   select * , row_number() over (partition by projectid order by APILoadDatetime desc) rn
   from tablename
) t where rn = 1

CodePudding user response:

select top 1 with ties * 
from tablename
order by row_number() 
over (partition by projectid order by APILoadDatetime desc) ;
  • Related