Search code examples
sqlsql-server-2000user-agent

Joining same table on itself


One of my table stores the UserAgent from the user's browser along with the corresponding UID associated with it, with some other data. This occurs every time a user logs in. So they will have many entries per user. I am trying to query this table to find some unique users based on qualities.

For example, I am trying to find only users that have used IE6 and no other browsers. The closest I can get so far is through this method:

select distinct (U.UID) from TABLE1 tb1
inner join TABLE1 tb2 on tb1.UID = tb2.UID
where tb1.UserAgent like '%MSIE 6.%'
and tb2.UserAgent like '%MSIE 6.%'

This seems to return users whom have used IE6 and any other browser as well. I am trying to find basically the opposite of this. Users that have used IE6 and IE6 only. I also tried the one below but didn't quite work either because a good chunk of this users had other entries with non IE6 browsers.

select distinct (U.UID) from TABLE1 tb1
inner join TABLE1 tb2 on tb1.UID = tb2.UID
where tb1.UserAgent like '%MSIE 6.%'
and tb2.UserAgent not like '%MSIE 6.%'

I think I am on the right track but could be way off here.

TIA!


Solution

  • Select user with user agent like '%MSIE 6.%' who do not have any other user agent. The inner query returns users who have not used '%MSIE 6.%'

    select distinct tb1.UID from TABLE1 tb1
    where tb1.UserAgent like '%MSIE 6.%' and
          NOT EXISTS ( select tb2.UID from TABLE1 tb2
                       where tb1.UID = tb2.UID AND 
                             tb2.UserAgent not like '%MSIE 6.%' )
    

    You can even use NOT IN instead of NOT EXISTS like tb1.UID NOT IN (...).

    select distinct tb1.UID from TABLE1 tb1
    where tb1.UserAgent like '%MSIE 6.%' and
          tb1.UID NOT IN ( select tb2.UID from TABLE1 tb2
                           where tb2.UserAgent not like '%MSIE 6.%' )
    

    The where clause condition tb1.UserAgent like '%MSIE 6.%' and can also be dropped without any side effects as the NOT and the inner query makes sure that the user's agent matches %MSIE 6.%