仅在满足特定条件时选择最后记录

时间:2015-04-22 12:29:44

标签: sql sql-server

我有一个包含ID,WorkerID,IsActive标志(1或0)和LocalTime的表。每次工作人员处于活动状态或未处于活动状态时,都会使用WorkerID,1或0标记记录和时间(LocalTime)创建记录。

我想插入一个新表:从这个表中,对于每个唯一的WorkerID,只有当此记录的IsActive标志为is时,才选择具有此唯一WorkerID的最新LocalTime的记录的WorkerID,LocalTime和LocalTime + Time。 1.如果对于WorkerID,具有最新LocalTime的记录的IsActive值为1,请选择它。否则,如果对于WorkerID,具有最新LocalTime的记录的IsActive值为0,则不要选择它。

示例:

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

只应选择ID为4的记录。

2 个答案:

答案 0 :(得分:0)

--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
)

答案 1 :(得分:0)

使用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