COMPLEX SQL PRACTICE:-From the doctors table, fetch the details of doctors who work in the same hospital but in different specialty.
From the doctors table, fetch the details of doctors who work in the same hospital but in different specialty.
Table Name: DOCTORS
Approach: Use self join to solve this problem. Self join is when you join a table to itself.
drop table doctors;
create table doctors
(
id int primary key,
name varchar(50) not null,
speciality varchar(100),
hospital varchar(50),
city varchar(50),
consultation_fee int
);
insert into doctors values(1, ‘Dr. Shashank’, ‘Ayurveda’, ‘Apollo Hospital’, ‘Bangalore’, 2500);
insert into doctors values(2, ‘Dr. Abdul’, ‘Homeopathy’, ‘Fortis Hospital’, ‘Bangalore’, 2000);
insert into doctors values(3, ‘Dr. Shwetha’, ‘Homeopathy’, ‘KMC Hospital’, ‘Manipal’, 1000);
insert into doctors values(4, ‘Dr. Murphy’, ‘Dermatology’, ‘KMC Hospital’, ‘Manipal’, 1500);
insert into doctors values(5, ‘Dr. Farhana’, ‘Physician’, ‘Gleneagles Hospital’, ‘Bangalore’, 1700);
insert into doctors values(6, ‘Dr. Maryam’, ‘Physician’, ‘Gleneagles Hospital’, ‘Bangalore’, 1500);
SOLUTION:
USING SELF JOIN:
select D1.*
from doctors D1 join doctors d2
on D1.ID <> D2.ID
and D1.HOSPITAL = D2.HOSPITAL
AND d1.speciality <> d2.speciality;
OUTPUT WILL BE 3RD AND 4TH ROW