[英]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. 我有一个包含ID,WorkerID,IsActive标志(1或0)和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).
每次工作人员处于活动状态或不处于活动状态时,都会使用WorkerID,1或0标志记录以及时间(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. 我想插入一个新表中:从该表中,对于每个唯一的WorkerID,仅当该记录的IsActive标志为1时,才为该唯一的WorkerID选择具有最新LocalTime的记录的WorkerID,LocalTime和LocalTime。对于WorkerID,具有最新LocalTime的记录的IsActive值为1,请选择它。 Else, if for a WorkerID the record with the latest LocalTime has an IsActive value of 0, don't select it.
否则,如果对于WorkerID,具有最新LocalTime的记录的IsActive值为0,请不要选择它。
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. 只能选择ID为4的记录。
--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
: 使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.