简体   繁体   中英

Select last records only if a certain condition is met

I have a table that contains ID, WorkerID, IsActive flag (1 or 0) and LocalTime. Every time a worker is active or is not active, a record is created with the WorkerID, a 1 or 0 flag record and a time (LocalTime).

I want to insert into a new table: from this table, for each unique WorkerID, select the WorkerID, LocalTime and LocalTime + Time of the record with the latest LocalTime for this unique WorkerID only if the IsActive flag for this record is 1. If for a WorkerID the record with the latest LocalTime has an IsActive value of 1, select it. Else, if for a WorkerID the record with the latest LocalTime has an IsActive value of 0, don't select it.

Example:

ID  WorkerID    IsActive    LocalTime
1   11      1       21/04/2015
2   22      0       22/04/2015
3   11      0       21/04/2015
4   22      1       22/04/2015

Only record with ID of 4 should be selected.

--get unique worker ids
select distinct WorkerId
from MyTable a
--which are active
where IsActive=1
--that don't have any worker ids on a more recent time
--(ignoring status as if there's a more recent active record for 
--this worker we want that record, not this one; if there's a more 
--recent inactive record we don't want this one anyway)
and not exists
(
    select top 1 1
    from MyTable b
    where b.WorkerId = a.WorkerId
    and b.LocalTime > a.LocalTime
)

With CROSS APPLY :

Select * From Worker w1
Cross Apply(Select * From(Select Top 1 * From Worker w2 
                          Where w1.WorkerID = w2.WorkerID
                          Order By w2.ID desc) t 
            Where t.IsActive = 1 And t.ID = w1.ID) ca

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