I don't know how to frame this question - so putting the sql statement directly here.
declare @tbl table(Id varchar(4),Userid varchar(10),Name varchar(max),Course varchar(max))
insert into @tbl values
('1','UserID1','UserA','Physics'),
('2','UserID2','UserB','Chemistry'),
('3,','UserID1','UserA','Chemistry')
Now,
To get a list of users who have taken Chemistry, I would write
select * from @tbl where Course='Chemistry'
Similarly for Physics, I would write
select * from @tbl where Course='Physics'
The problem is when I try to write the query "get a list of students who haven't taken Physics". Without thinking much, I wrote this
select * from @tbl where Course!='Physics'
and it results in, which is wrong (it is getting details about UserA - though he has registered in Physics)
Id Userid Name Course
2 UserID2 UserB Chemistry
3, UserID1 UserA Chemistry
To fix this, I rewrote the query like this - but somehow I think this is not the right way.
select * from @tbl where Course!='Physics'
and Userid not in (select Userid from @tbl where Course='Physics')
Please help!