Interview Question
NonesCountry: United States
Interview Type: In-Person
select A,(la - c) as total_time_spend from (select A,B,c,lag(c,1) over (partition by A order by A) as la from t4 ) where la is not null;
or
with exp as ( select A,max(c) as logout,min(c) as login from t4 group by A)
SELECT A,(logout - login) as total_spent_time from exp;
or
with exp as (
select a,max(c) as logout,min(c) as login from t4 group by a order by a
)
select a, (logout - login) as total_time_spend from exp;
Here A is name, B is event, C is event time
This query gives the hours spent per user per day.
with cte as
( select name,event,time,row_number() over(partition by date(event_time), name order by event_time) as rnm from table)
select a.name,date(a.event_time),sum(datediff(hr,b.event_time,a.event_time)) from cte a join cte b on a.rnm=b.rnm-1 and a.event='login' group by a.name,date(a.event_time)
)
Following works if multiple login by student A
create table logins(name varchar(2),event varchar(10),time integer);
insert into logins values
('A','login',5),
('B','login',6),
('A','logout',7),
('B','logout',8),
('A','login',9),
('A','logout',10)
with tab as(
select name,event,time,lead(time)over(partition by name order by time) as timeout
from logins)
select name,time,timeout,timeout-time from tab where event='login';
The question seems incomplete, and I would prefer to log the session id for ease of request.
However...
- jk August 20, 2019