简体   繁体   中英

SQL Server : select last record for each employee

The below query gets employees log (attendance) information at multiple terminals (outlets).

For example if one employee visited three outlets in different days I want to get last log information (last outlet he visited).

Query:

select 
    [EmpCode],
    Name,
    max(convert(datetime, [LogDate])) as [Last Log date],
    Outlet.abr as [Last Log Location]
from
    AccessLog
inner join
    GEmp on GEmp.EmpCode = AccessLog.EmployeeID
inner join
    Outlet on Outlet.Code = AccessLog.TerminalID
where   
    InOut = '0'
group by 
    GEmp.EmpCode, Name, Outlet.abr

Output:

EmpCode Name    Last Log date   Last Log Location
--------------------------------------------------
362334  Emp1    10/4/2017       loc1
362334  Emp1    11/4/2017       loc2
362334  Emp1    5/30/2017       loc3
362336  Emp2    10/6/2017       loc1
362336  Emp2    11/4/2017       loc2

Desired output:

EmpCode Name    Last Log date   Last Log Location
-------------------------------------------------
362334  Emp1    11/4/2017        loc2
362336  Emp2    11/4/2017        loc2

I'm not able to test but here is the correct method:

Select *
    From 
   (
   Select ilv.*, row_number () over (partition by empcode order by logdate desc)
   r
   From
   (...) ilv 
   ) ilv2
   Where r=1

Only note is if the same last date occurs multiple times, you will need a tie breaker. As it stands that query above does not have one and thus is not idempotent.

Use row_number() :

select e.Name, al.LogDate, o.abr
from (select al.*,
             row_number() over (partition by al.EmployeeId order by al.LogDate desc) as seqnum
      from AccessLog al
      where al.InOut = 0
     ) al join
     GEmp e
     on e.EmpCode = al.EmployeeID join
     Outlet o
     on o.Code = al.TerminalID
where al.seqnum = 1;

Notes:

  • I added table aliases which are abbreviations for the table. This makes the query easier to write and to read.
  • I qualified all column names (hopefully correctly!) so it is clear where the data is coming from.
  • I removed the single quotes around '0' . My assumption is that the value is actually numeric.
  • The solution to your problem is the use of row_number() in the subquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM