Here is my user log table
ID USERID TIME TYPE
1 6 12:48:45 OUT
2 11 12:08:46 IN
3 6 12:18:45 IN
4 6 12:08:45 IN
5 9 12:06:44 IN
6 11 11:08:46 IN
I need get currently loggedin user and last logged in time in SQL Server . Output like this
ID USERID TIME TYPE
2 11 12:08:46 IN
5 9 12:06:44 IN
The solution consists in using 2 CTEs, the first one contains all logged in users and the second contains all logged out users. Then the final select take those logged-in users that are not yet logged-out.
WITH loggedIn
AS
(
SELECT userId, MAX([time]) LastLogIn
FROM logtable
WHERE [type]='IN'
GROUP BY userId
),
loggedOut
AS
(
SELECT userId, MAX([time]) LastLoginOut
FROM logtable
WHERE [type]='OUT'
GROUP BY userId
)
SELECT loggedIn.userId, loggedIn.LastLogin
FROM loggedIn
WHERE
userId NOT IN (SELECT userId FROM loggedOut)
--AND LastLogIn > @currentTime
Using your test data..
Declare @logintable table (id int, userid int, time datetime, type varchar(3))
Insert into @logintable values (1,6,'12:48:45','OUT')
Insert into @logintable values (2,11,'12:08:46','IN')
Insert into @logintable values (3,6,'12:18:45','IN')
Insert into @logintable values (4,6,'12:08:45','IN')
Insert into @logintable values (5,9,'12:06:44','IN')
Insert into @logintable values (6,11,'11:08:46','IN')
..this query should get you the result set you are after
SELECT
a.*
FROM
@logintable a
INNER JOIN
(SELECT userid, MAX(time) as time FROM @logintable b GROUP BY userid) b
ON
a.userid = b.userid AND a.time = b.time
WHERE
a.type = 'IN'
ORDER BY
a.id
The subquery finds the most recent entry for each user and compares it with the record we're currently looking at (that must be an 'IN' record). By doing this we automatically find logged in users.
Note that I have joined on MAX(TIME)
here where it would be nicer to join on MAX(ID)
- I would guess that in production your ID column would be sequential (ideally an identity column) and so the bigger the value of id
the bigger the value of time
.
The above query gives these results
ID UserID Time Type
2 11 1900-01-01 12:08:46.000 IN
5 9 1900-01-01 12:06:44.000 IN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.