Home > Blockchain >  SQLITE Split Datetime to Logon/Logoff
SQLITE Split Datetime to Logon/Logoff

Time:08-16

Hy, i want to split the time to 2 columns by Event type.

My Table looks like this:

User EventType Time
name1 Logon 14.08.2022 23:51:12
name2 Logoff 12.08.2022 09:12:44
name2 Logon 11.08.2022 23:51:01
name1 Logoff 16.08.2022 08:27:55

And i want to split the Time with EventType like this in SQLite:

User Logon Logoff
name1 14.08.2022 23:51:12 16.08.2022 08:27:55
name2 11.08.2022 23:51:01 12.08.2022 09:12:44

any ideas?

CodePudding user response:

assuming there is no double logons without logoff, as in your example, you can do this:

select user, 
       logon_time, 
       logoff_time 
  from (select user, 
               time logon_time,
               lead(time) over(partition by user order by time) logoff_time,
               event_type
          from test_table)
 where event_type = 'Logon';

The LEAD function takes value from next line using ordering from "order by" part. In your case a logoff event takes place only after a logon, so it might working

db_fiddle

CodePudding user response:

WITH
  session AS
(
  SELECT
    SUM(
      CASE WHEN eventtype = 'logon' THEN 1 ELSE 0 END
    )
    OVER (
      PARTITION BY username
          ORDER BY eventtime
    )
      AS user_session_id,
    *
  FROM
    yourData
  WHERE
    eventtype IN ('logon', 'logoff')
)
SELECT
  username,
  user_session_id,
  MIN(CASE WHEN eventtype = 'logon'  THEN eventtime END),
  MIN(CASE WHEN eventtype = 'logoff' THEN eventtime END)
FROM
  session
GROUP BY
  username,
  user_session_id
  • Related