I have a table in which I’m recording logins/logouts. Schema and sample data: http://sqlfiddle.com/#!2/e1b35/1
I need to create stored procedure which will print sum of (logout-login) times for an user and date (duration of using application for user on date). In column type I represents login and O logout.
Input parameters: @username, @date. Output: time.
You need to identify all groups of logins that are related to each other. The way I would do this is by finding the logout associated with logins. You are dealing with log data, so don’t be surprised if there are multiple logins with no logout.
Now, you can use the username and LogoutTime as a pair for aggregation to get what you want:
Note that you specify SQL Server as a tag, but the SQL Fiddle is for MySQL; date functions tend to differ among databases.
And, if you are using SQL Server 2012, there is an easier way. You should specify that if it is the case.