2017-08-14 67 views
0

在SQL Server中,如何根據「進入/退出」列來獲取員工進出狀態?例如,如果員工的最後一條記錄是「輸入」,那麼他就是「進入」。如果最後的記錄是'退出',那麼他'出'。對於ID = 111,IN_OUT應該是 '中',和id = 222應該是 '出'根據「進入/退出」列獲得員工「進出」狀態

+-----+---------------------+------------+ 
| id |  timestamp  | status | 
+-----+---------------------+------------+ 
| 111 | 01/01/2017 07:00:10 | enter  | 
| 222 | 01/01/2017 01:10:29 | enter  | 
| 111 | 01/01/2017 18:20:17 | exit  | 
| 111 | 01/02/2017 08:20:34 | enter  | 
| 333 | 01/02/2017 06:20:11 | enter  | 
| 222 | 01/02/2017 10:10:47 | exit  | 
+-----+---------------------+------------+ 

我明白我應該用case語句,但下面的代碼將無法正常工作

select id, case 
     when status = 'enter' then 'in' 
     when status = 'exit' then 'out' 
     else 'n/a' 
     end as in_out 
from table1 

回答

1

如果我理解正確,你可以按照以下查詢:

Select Id, case when [status] = 'enter' then 'in' else 'out' end as In_out 
    from (
    Select *, RowN = row_number() over(partition by id order by [timestamp] desc) from #timedata 
) a Where a.RowN = 1 

輸出如下:

+-----+--------+ 
| Id | In_out | 
+-----+--------+ 
| 111 | in  | 
| 222 | out | 
| 333 | in  | 
+-----+--------+
+0

偉大的解決方案,謝謝! –

0

訣竅是找到第一個出口後面的每個輸入

select in.id, 
     case coalesce(min(out.status), in.status) 
     when 'enter' then 'in' 
     when 'exit' then 'out' 
     else 'n/a' -- I suggest: coalesce(out.status, in.status) + '??' 
     end as 'status' 
from table1 as in 
left 
join table1 as out 
on in.id = out.id 
and in.timestamp <= out.timestamp 
and in.status = 'enter' 
and out.status = 'exit' 
group by in.id, in.status 

此查詢查找最小出口每個{ID,時間戳} 輸入對。它假設在進入之前沒有退出(建築物中沒有人)。這需要單獨驗證。

每當我爲這樣的報告寫入數據時,我儘量不要壓制意想不到的輸入,而是讓它流過。如果你把一切的不進入退出N/A,在某些時候你將不得不找出什麼是生產這些N/A的。不妨在報告中打印出來;它會讓你的工作更輕鬆。