2016-10-06 47 views
1

我有一個表,拿着時鐘輸入/輸出時間爲幾個員工:mssql - 使用內部連接在同一行顯示列值?

username   datetime     action 

test.user   2016-10-05 07:30:49  0 
test.user   2016-10-05 08:50:00  1 
test.user   2016-10-05 08:53:49  0 
test.user   2016-10-05 13:35:47  1  

我想獲得與包含用戶名的每一行的結果集,並在該用戶名/縮小操作的對時鐘的(0時鐘輸入,1時鐘輸出)。

我到目前爲止是這樣的:

select a.username, a.datetime as clockIN, b.datetime as clockOUT 
from attendance a 
inner join 
attendance b 
on 
(
a.username = b.username 
and datepart(dd, a.datetime) = datepart(dd, b.datetime) 
and datepart(mm, a.datetime) = datepart(mm, b.datetime) 
and datepart(yy, a.datetime) = datepart(yy, b.datetime) 
and a.action = 0 
and b.action = 1 
and a.datetime < b.datetime 
) 
order by a.datetime asc 

這是結果

username  clockIN    clockOUT 

test.user  2016-10-05 07:30:00 2016-10-05 08:50:00 
test.user  2016-10-05 07:30:00 2016-10-05 13:35:47  
test.user  2016-10-05 08:53:49 2016-10-05 13:35:47 

期望的結果將是:

username  clockIN    clockOUT 

test.user  2016-10-05 07:30:00 2016-10-05 08:50:00 
test.user  2016-10-05 08:53:49 2016-10-05 13:35:47 

如何ommit的任何想法第二排從結果?

謝謝!

+0

什麼是正在被省略了第二個記錄的邏輯是什麼? –

+1

如果兩個clockOUT具有相同的值但不同的clockIN值會怎樣? – jarlh

+1

我很困惑...用戶同時檢查兩次並在不同的時間檢查嗎?還是他們分開用戶? – Danieboy

回答

0

如何:

SELECT 
    a1.username, a1.datetime as clockIN 
, (SELECT top 1 a2.datetime FROM #attendance a2 
    where a1.username = a2.username and a2.action = 1 and a2.datetime > a1.datetime order by a2.datetime) AS clockout 
FROM #attendance a1 WHERE action = 0 
+0

謝謝!很棒! – Andreas