2010-04-26 158 views
0

運行SQL Server 2008,我肯定是一個新的SQL用戶。SQL Server查詢問題

我有一個具有4列的表格:

EmpNum, User, Action, Updatetime 

用戶登錄到,進出的系統的,它在數據庫中登記。例如,如果用戶1登錄到系統中,然後進行5分鐘後,一個簡單的查詢(選擇更新*)看起來像:

EmpNum User Action Updatetime 
1  User1 I  2010-01-01 23:00:00:000 
1  User1 O  2010-01-01 23:05:00:000 

我想查詢Empnum,用戶,操作,我(及時),O(不及時)和總時間。

+0

還能有每個用戶的多個條目(登錄/註銷)表中?你想看看所有的時期嗎? – 2010-04-26 04:43:03

+0

哦,是的。所以,User1每天可能會有50次I,O操作。 – Lp1 2010-04-26 12:39:08

回答

0
Select T1.EmpNum, T1.User, T1.UpdateTime As TimeIn 
, (Select Min(T2.UpdateTime) 
     From Table As T2 
     Where T2.EmpNum = T1.EmpNum 
     And T2.User = T1.User 
     And T2.Action = 'O' 
And T2.UpdateTime > T1.UpdateTime) As TimeOut 
From Table As T1 
Where Action = 'I' 

編輯在你的意見,你問TimeWorked。由於您使用的是SQL Server 2008,因此可以使用外部應用來計算每個時間行的外出時間。那麼使用DateDiff就很簡單了。

Select T1.EmpNum, T1.User 
    , T1.UpdateTime As TimeIn 
    , TimeOut.UpdateTime As TimeOut 
    , DateDiff(mi, T1.UpdateTime, TimeOut.UpdateTime) As TimeWorkedInMinutes 
From Table As T1 
    Outer Apply (
       Select Min(T2.UpdateTime) As UpdateTime 
       From Table As T2 
       Where T2.EmpNum = T1.EmpNum 
        And T2.User = T1.User 
        And T2.Action = 'O' 
        And T2.UpdateTime > T1.UpdateTime 
       ) As TimeOut 
Where Action = 'I' 
+0

謝謝你們兩位,我現在要試一試。 – Lp1 2010-04-26 12:07:40

+0

Thomas, 您的查詢是成功的,我只是想知道如何在結果中再添加一列。最後,我想要一個TimeWorked,它給出了用戶在系統中的總時間。 我仍然試圖圍繞T1和T2的包裝頭。當然今天學到了一些新東西。 – Lp1 2010-04-26 12:21:42

+0

再次感謝您的幫助。你們救了我的理智。 – Lp1 2010-04-26 13:12:02

2

你可以嘗試像

DECLARE @Table TABLE(
     EmpNum Int, 
     [User] VARCHAR(10), 
     Action VARCHAR(1), 
     Updatetime DATETIME 
) 

INSERT INTO @Table SELECT 1,'User1','I','2010-01-01 23:00:00:000' 
INSERT INTO @Table SELECT 1,'User1','O','2010-01-01 23:05:00:000' 
INSERT INTO @Table SELECT 1,'User1','I','2010-01-01 23:10:00:000' 
INSERT INTO @Table SELECT 1,'User1','O','2010-01-01 23:25:00:000' 

SELECT *, 
     DATEDIFF(mi, InTime, OutTime) Period 
FROM (
      SELECT EmpNum, 
        [User], 
        UpdateTime InTime, 
        ( SELECT TOP 1 
           Updatetime 
         FROM @Table 
         WHERE EmpNum = t.EmpNum 
         AND  Action = 'O' 
         AND  Updatetime > t.Updatetime 
         ORDER BY Updatetime 
        ) OutTime 
      FROM @Table t 
      WHERE Action = 'I' 
     ) sub 

輸出

EmpNum  User  InTime     OutTime     Period 
----------- ---------- ----------------------- ----------------------- ----------- 
1   User1  2010-01-01 23:00:00.000 2010-01-01 23:05:00.000 5 
1   User1  2010-01-01 23:10:00.000 2010-01-01 23:25:00.000 15