2015-04-22 81 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 
相關問題