Crear una consulta SQL para recuperar los registros más recientes


Estoy creando un módulo de status board para mi equipo de proyecto. El tablero de estado permite al usuario establecer su estado como entrada o salida y también puede proporcionar una nota. Planeaba almacenar toda la información en una sola tabla ... y ejemplo de los datos sigue:

Date               User         Status    Notes
-------------------------------------------------------
1/8/2009 12:00pm   B.Sisko      In        Out to lunch    
1/8/2009 8:00am    B.Sisko      In  
1/7/2009 5:00pm    B.Sisko      In    
1/7/2009 8:00am    B.Sisko      In    
1/7/2009 8:00am    K.Janeway    In   
1/5/2009 8:00am    K.Janeway    In    
1/1/2009 8:00am    J.Picard     Out       Vacation  

Me gustaría consultar los datos y devolver el estado más reciente de cada usuario, en este caso, mi consulta devolvería los siguientes resultados:

Date               User         Status    Notes
-------------------------------------------------------  
1/8/2009 12:00pm   B.Sisko      In        Out to lunch    
1/7/2009 8:00am    K.Janeway    In   
1/1/2009 8:00am    J.Picard     Out       Vacation  

Estoy tratando de averiguar la TRANSACT-SQL para hacer esto ¿pasar? Cualquier ayuda sería apreciada.

Author: Pure.Krome, 2009-06-26

4 answers

Agregue en una tabla derivada subconsulta y luego únase a ella.

 Select Date, User, Status, Notes 
    from [SOMETABLE]
    inner join 
    (
        Select max(Date) as LatestDate, [User]
        from [SOMETABLE]
        Group by User
    ) SubMax 
    on [SOMETABLE].Date = SubMax.LatestDate
    and [SOMETABLE].User = SubMax.User 
 67
Author: cmsjr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-16 02:56:14

De otra manera, esto escaneará la tabla solo una vez en lugar de dos veces si usa una subconsulta

Solo sql server 2005 y superiores

select Date, User, Status, Notes 
from (
       select m.*, row_number() over (partition by user order by Date desc) as rn
       from [SOMETABLE] m
     ) m2
where m2.rn = 1;
 47
Author: SQLMenace,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-12 04:20:30

La tabla derivada funcionaría, pero si esto es SQL 2005, un CTE y ROW_NUMBER podrían ser más limpios:

WITH UserStatus (User, Date, Status, Notes, Ord)
as
(
SELECT Date, User, Status, Notes, 
     ROW_NUMBER() OVER (PARTITION BY User ORDER BY Date DESC)
FROM [SOMETABLE]
)

SELECT User, Date, Status, Notes from UserStatus where Ord = 1

Esto también facilitaría la visualización de los estados x más recientes de cada usuario.

 7
Author: 2 revs, 2 users 71%Ira Pfeifer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-16 03:22:53

Otra manera fácil:

SELECT Date, User, Status, Notes  
FROM Test_Most_Recent 
WHERE Date in ( SELECT MAX(Date) from Test_Most_Recent group by User)
 4
Author: Mahesh RG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-16 15:03:11