SQL Server – How to SELECT Last Date from Multiple Values

greatest-n-per-groupquerysql serversql-server-2012

I have this table:

enter image description here

I want to make a query that allows me to show the last value in fecha_gestion
grouped by NitSec. It would be something like this:

SELECT id_log, fecha_gestion, nitsec 
FROM table 
GROUP BY nitsec 
ORDER BY fecha_gestion DESC

The result I want is this:

ID_log | fecha_gestion    | nitsec  
6      | 2020-01-03 09:52 | 5443
11     | 2020-01-03 10:12 | 1 
15     | 2020-01-03 10:23 | 3286

After doing this I need an inner join (but I can do it easily). Thanks in advance.

Best Answer

One possible approach is to number rows appropriately using ROW_NUMBER():

SELECT id_log, fecha_gestion, nitsec
FROM (
   SELECT 
      id_log, fecha_gestion, nitsec,
      ROW_NUMBER() OVER (PARTITION BY nitsec ORDER BY fecha_gestion DESC) AS rn
   FROM table 
) t
WHERE rn = 1