2017-03-27 57 views
0

我目前正在努力從時鐘輸出系統中獲取每位員工的持續時間。 基本上我有一個交易表,它保存了所有的時鐘信息。 例如,表中的記錄是這樣的:如何獲得時鐘輸出系統中員工時鐘的持續時間

Name  |  Time   | Action 
employee A  | 20170327 08:30:00 | in 
employee B  | 20170327 08:35:00 | in 
employee A  | 20170327 12:30:00 | out 
employee A  | 20170327 13:20:00 | in 
employee B  | 20170327 17:30:00 | out 
employee A  | 20170327 17:20:00 | out 
employee C  | 20170327 09:00:00 | in 

對於自來水或時鐘出水龍頭每個時鐘,將有此表中插入一個記錄,我想每一個最近2之間的持續時間爲同一人的記錄,因此查詢結果,我想會是這樣的:

Name | Duration From | Duration To 
    A  | 20170327 08:30:00 | 20170327 12:30:00 
    A  | 20170327 13:20:00 | 20170327 17:20:00 
    B  | 20170327 08:35:00 | 20170327 17:30:00 
    C  | 20170327 09:00:00 | NULL 

這裏是我有這麼遠的查詢:

Select name,min(StartTime) as DurationFrom,max(EndTime) as DurationTo 
from 
    (select name, case Action when 'in' then time end as startTime, 
       case Action when 'out' then time end as endTime 
from dbo.transaction)main 
    group by name 

這是迄今爲止的結果:

Name | Duration From | Duration To 
    A  | 20170327 08:30:00 | 20170327 17:20:00 
    B  | 20170327 08:35:00 | 20170327 17:30:00 
    C  | 20170327 09:00:00 | NULL 

有人可以幫我解決這個問題嗎?非常感謝提前。

+0

您正在使用哪種版本的sql server? –

回答

0

你需要加入所有的水龍頭。

select s.name, s.[time] as startTime, min(e.[time]) as endTime 
from dbo.[transaction] s 
left join dbo.[transaction] e 
on s.name = e.name 
and e.Action='out' 
and s.[time]< e.[time] 
where s.Action='in' 
group by s.name, s.[time] 
+1

您的where子句將「left join」更改爲「inner join」。右表中的所有條件都應放在'on'子句中。 –

+0

此外,關鍵字必須包含在'[]' - '[transaction],[end]'中。 –

+0

感謝提醒我,我已經更正了答案。 :) –