Reputation: 45
Display the salesmen id, salesmen name and location of those salesmen who are co-located.
I have used self join to solve it
select s.sid, s.sname, s.location
from salesman s
inner join salesman ss on s.location = ss.location
where s.location=ss.location
Salesman Table
SID SNAME LOCATION
1 Peter London
2 Michael Paris
3 John Mumbai
4 Harry Chicago
5 Kevin London
6 Alex Chicago
Expected output
Expected Result
SID SNAME LOCATION
5 Kevin London
6 Alex Chicago
1 Peter London
4 Harry Chicago
Upvotes: 0
Views: 6308
Reputation: 87
Probably something like this:
select s.sid, s.sname, s.location
from salesman s
inner join salesman ss
on s.sid <> ss.sid
and s.location = ss.location
Upvotes: 1
Reputation: 36
I have assumed that you are not particular about sequence which you have shown in expected output and used join which is much quicker .
select s.sid, s.sname, s.location
from salesman s
inner join (
select location from salesman group by location having count(*) >1
) ss on s.location = ss.location
Upvotes: 2
Reputation: 164069
With EXISTS:
select s.*
from salesman s
where exists (
select 1
from salesman
where sid <> s.sid and location = s.location
)
Upvotes: 1
Reputation: 48770
You can use a subquery to find the repeated locations, and then get all salesman on those locations in the main query, as in:
select *
from salesman
where location in (
select location
from salesman s
group by location
having count(*) > 1
)
Upvotes: 0