Query group by pair of column result

前端 未结 2 637
一个人的身影
一个人的身影 2021-01-15 11:15

Currently my dataset consist of 4 columns, id, status, user_id, created_date

so after a while the data can be lik

相关标签:
2条回答
  • 2021-01-15 11:30

    You can do it with a left join and then subtract the 2 dates:

    select 
      t.id, 
      t.action_date login_date, tt.action_date logout_date,
      t.user_id,
      (tt.action_date - t.action_date) / 100 session_time
    from (
      select * from session where status = 'LOGIN'  
    ) t left join (
      select * from session where status = 'LOGOUT'    
    ) tt on tt.user_id = t.user_id and 
      tt.action_date = (
        select min(action_date) from session
        where status = 'LOGOUT' and user_id = t.user_id and action_date > t.action_date
      )
    

    See the demo.
    Results:

    | id  | login_date          | user_id | logout_date         | session_time |
    | --- | ------------------- | ------- | ------------------- | ------------ |
    | 1   | 2019-07-16 07:06:55 | Bob     | 2019-07-16 07:29:13 | 22.58        |
    | 3   | 2019-07-16 07:30:31 | Bob     | 2019-07-16 07:49:50 | 19.19        |
    | 5   | 2019-07-16 08:05:55 | Tom     | 2019-07-16 08:15:13 | 9.58         |
    | 7   | 2019-07-16 09:13:55 | John    | 2019-07-16 09:20:13 | 6.58         |
    
    0 讨论(0)
  • 2021-01-15 11:38

    Simple implementation over provided inputs. i have data set like:

    select id, stat[status],dater[Date], name[Name] from tablelogin
    

    Data Extraction:

    Select t1.id, t1.dater[login], t2.dater[logout], t1.name[name], datediff(day,t1.dater, t2.dater)[days] from tablelogin t1, tablelogin t2 where t1.name=t2.name and t2.id>t1.id and t2.stat='logout'
    

    you need to work on logic and control, when records grows the above query may produce different results.

    0 讨论(0)
提交回复
热议问题