sql server - sql query for logins for days -
my question table:
userid logintime logouttime 1 1/8/17 10am 1/8/17 9pm 2 1/8/17 9am 1/8/17 10pm 3 1/8/17 11am 1/8/17 6pm 1 2/8/17 11am 2/8/17 7pm 2 2/8/17 6am 2/8/17 4pm 3 2/8/17 8am 2/8/17 3pm 1 3/8/17 4am 3/8/17 1pm 2 3/8/17 11am 3/8/17 11pm 3 3/8/17 5am 3/8/17 5pm
i need sql query time gap between user 1st day second day
example answer table:
userid logintime logouttime timegap 1 1/8/17 10am 1/8/17 9pm 25 hours 1 2/8/17 11am 2/8/17 7pm
time gap userid=1 1/8/17 10am 2/8/17 11am 25 hours
below use common table expression (cte) on existing table increments userid , ordered logintime earliest last, join joining on row number +1
with cte as( select userid, logintime, logouttime, row_number() on (partition userid order logintime asc nulls last) rn table ) select cte.userid, cte.logintime, cte.logouttime, (cte.logintime-cte2.logintime) timegap cte left join on cte cte2 on (cte.rn +1)=cte2.rn , cte.userid=cte2.userid
Comments
Post a Comment