I have a table like this:
ID | username | domain | operation| datetime
---+----------+--------+----------+--------------------
1 | john | depA | 'login' | 2012-09-22 13:00:00
2 | mary | depA | 'login' | 2012-09-22 13:10:00
3 | john | depA | 'login' | 2012-09-24 13:25:00
4 | john | depA | 'logout' | 2012-09-24 13:55:00
I would like to get (SELECT DISTINCT) all “username, domain” which its last operation is login (which didn’t logout by last) during the last 20 hours (datetime).
The idea is to get “all users currently at a session.”
I would like the result to be processed in just one query.
Any ideas, please? I could not find a way of getting the result just with T-SQL.
You can use a common table expression to filter out the date, and then use it twice in the query to get the most recent activity for each user: