2015-04-22 27 views
0

我有一个包含ID,WorkerID,IsActive标志(1或0)和LocalTime的表。每当工作人员处于活动状态或未处于活动状态时,将使用WorkerID,1或0标记记录和时间(LocalTime)创建记录。只有在满足特定条件时才选择最后一条记录

我想插入到一个新表中:对于每个唯一的WorkerID,从这张表中选择带有最新LocalTime的记录的WorkerID,LocalTime和LocalTime +是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 

只有具有的4 ID记录应该被选中。

+1

的可能重复[选择仅在某些条件得到满足最后一个记录(http://stackoverflow.com/questions/29796848/select-last-record-只有如果某种条件得到满足) – jarlh

+1

请编辑您的原始问题,而不是发布另一个问题。 –

+0

你的意思是“LocalTime和LocalTime +最新的LocalTime记录的时间”?请举个例子。 – 1010

回答

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 
) 
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 
相关问题