2017-03-12 191 views
-1

我有一張桌子,我在一臺機器上管理用戶登錄。根據活動類型,我確定它是否是登錄或註銷。我被要求生成關於用戶登錄/註銷的報告。它適用於所有班次,但不適用於午夜班次。需要查詢諮詢

樣品表:

User_id Activity_code timestamp 
1  login   2016-03-28 11:10:00 
1  logout  2016-03-28 19:45:00 
2  login   2017-02-15 23:00:00 
2  logout  2017-02-16 07:00:00 

如果我按時間戳,我得到的報告正確地爲用戶ID1,而不是用戶2

desc pmevents_bkp 

Name   Null? Type 
------------- ------- -------------- 
EVENTTYPE  NOT NULL NUMBER(4) 
USERID     CHAR(32) 
JOBNUMBER    NUMBER(11) 
TIMESTAMP  NOT NULL DATE 
SEQUENCENUMBER   NUMBER(8) 

SQL >select * from pmevents_bkp; 

EVENTTYPE USERID       JOBNUMBER TIMESTAMP SEQUENCENUMBER 
---------- -------------------------------- ---------- --------- -------------- 
     101 JBOND 007        12345 11-MAR-17   12345 
     101 JBOND 007        12345 12-MAR-17   12345 
     101 JBOND 008        3245 11-MAR-17   3245 
     100 JBOND 007        12345 11-MAR-17   3245 

SQL >select to_char(timestamp, 'MM/DD/YYYY'), 
    2 userid, 
    3 MIN(timestamp) KEEP (DENSE_RANK FIRST ORDER BY eventtype) "Login", 
    4 MAX(timestamp) KEEP (DENSE_RANK LAST ORDER BY eventtype) "Logout" 
    5  FROM pmevents_bkp 
    6  where timestamp BETWEEN TO_DATE('01-mar-17','DD-MON-YY') AND TO_DATE('30-mar-17','DD-MON-YY') 
    7 and (eventtype = '100' 
    8 or eventtype = '101') 
    9 group by to_char(timestamp, 'MM/DD/YYYY'),userid; 

TO_CHAR(TI USERID       Login  Logout 
---------- -------------------------------- --------- --------- 
03/11/2017 JBOND 007      11-MAR-17 11-MAR-17 
03/11/2017 JBOND 008      11-MAR-17 11-MAR-17 
03/12/2017 JBOND 007      12-MAR-17 12-MAR-17 
+4

什麼是正確的結果?你試過什麼查詢?不要害羞。 –

+1

您是否意味着您想按登錄時間戳進行分組,並將登出時間戳與匹配的登錄時間戳相關聯,而不管第二天是否登出? – marcothesane

+0

同一個user_id只能登錄和登出一次嗎?或每天一次?或每天幾次? – marcothesane

回答

0

這工作,無論是否有多個登錄/從每天或者註銷丟失:

select * 
from 
(
    select User_id, 

     -- login timestamp 
     case when Activity_code = 'login' then timestamp end as Login, 

     -- next row's timestamp (only if it's a logout) 
     lead(case when Activity_code = 'logout' then timestamp end) 
     over (partition by User_id 
      order by timestamp) as Logout 
    from tab 
) dt 
where Logon is not null -- only the login rows 
+0

謝謝。我會嘗試。 – RookieDBA

+0

請查看其他詳細信息: – RookieDBA

+0

@RookieDBA:示例數據中的'activity_code'在哪裏,它是'event_type'?沒有時間的一部分,你的例子是無用的。不過,我的方法應該工作。 – dnoeth

0

@dnoeth:

select to_char(timestamp, 'MM/DD/YYYY'), 
userid, 
MIN(timestamp) KEEP (DENSE_RANK FIRST ORDER BY eventtype) "Login", 
MAX(timestamp) KEEP (DENSE_RANK LAST ORDER BY eventtype) "Logout" 
FROM formscan.pmevents_bkp 
where timestamp BETWEEN TO_DATE('01-mar-17','DD-MON-YY') AND TO_DATE('30-  
mar-17','DD-MON-YY') 
and (eventtype = '100' 
or eventtype = '101') 
group by to_char(timestamp, 'MM/DD/YYYY'),userid; 
+0

這應該是你的問題的一部分,而不是一個答案。這是您現有的查詢,這與我的答案完全不同。只需更改CASE邏輯以匹配'activity_code',100 =登錄和101 =註銷? – dnoeth