I have a table that has the following format (int, int, DateTime)
Id | IdOperacion | Fecha 1 | 1 | 08/03/2021 10:00:00.00 2 | 2 | 08/03/2021 10:10:00.00 3 | 3 | 08/03/2021 10:20:00.00 4 | 1 | 08/03/2021 11:00:00.00 5 | 2 | 08/03/2021 11:10:00.00 6 | 3 | 08/03/2021 11:20:00.00
I have tried to obtain the last dates so that the table looks like this:
Id | IdOperacion | Fecha 4 | 1 | 08/03/2021 11:00:00.00 5 | 2 | 08/03/2021 11:10:00.00 6 | 3 | 08/03/2021 11:20:00.00
Removing the operations with last date but being variable I don't know how to do it:
SELECT Id, IdOperacion, Fecha FROM Tabla WHERE Fecha >= Convert(datetime, GETDATE())
There are probably several options to handle your question. I propose one based on formatting the date so that it only contains the date and time (without minutes and seconds) and use this to filter the data.
The first part is to get the date with just the time. For that we use
convert
:the first part returns the date as
yyyymmdd
, and the second part returns the time inhh:mm:ss
. But since in the conversion we usechar(2)
, we get only the first two characters, that is, the time. The result it returns is something like this:Once that problem is solved, we have to get what is the largest date/time in our table. This is simple: we simply order by date in descending order and we are left with the first result:
The last step would be to obtain the rows of the table whose converted date matches the data of this subquery:
We will split the problem in two. First we get the last date for each element using the aggregation function
MAX()
, then we will join the result (one row per idOperacion) with the table query, getting only the last value.