Question : SQL 2005 - query to exclude session records for web application

I have a table that stores the userid, session_id, and session_type when a user signs in the web application and when the user logs out of the web application. When the user signs in, it creates a row for session_type = '4'. When the user logs out, it creates a row for session_type = '5'. The session_id and userid is the same for both rows.  For example

User_Name          Session_id          Session_type
12345                   2222                    4
98765                   3333                    4
56789                   4444                    4
12345                   2222                    5

In this example three users signed into the web application and one of the users logged out. I need the query to return only current users signed in. This example would need to return 2 records.  My query is

select user_name,   session_id, session_type
from table
where session_type in ('4','5')

The results return all 4 records. How do I exclude records where session_id contains a session_type both '4', and '5'.  Thanks!

Answer : SQL 2005 - query to exclude session records for web application

select user_name,   session_id, session_type
from table t
where session_type = '4'
and not exists (
select 1 from table where user_name = t.user_name and session_type = '5'
)
Random Solutions  
 
programming4us programming4us