患者不使用的医生
select distinct d.number, d.surname
from doctor d
left join ward w on w.consultant = d.number
left join admission ad on ad.ward = w.code
left join patient p on p.code = ad.patient
where p.code is null
患者使用的医生
select distinct d.number, d.surname
from doctor d
join ward w on w.consultant = d.number
join admission ad on ad.ward = w.code
join patient p on p.code = ad.patient
架构(用于测试):
select * into patient
from (
select 'A102' [code], 'Harris' [surname], 'Lucy' [lastname] union all
select 'B372', 'Rossini', 'Peter' union all
select 'B534', 'Johnson', 'Nadia' union all
select 'B444', 'Johnson', 'Juigi' union all
select 'S555', 'Rose', 'Jean') as p
select * into admission
from (
select 'A102' [patient], null [admitted], NULL [discharged], 'A' [ward] union all
select 'A102', null, NULL, 'A' union all
select 'S555', null, NULL, 'B' union all
select 'B444', null, NULL, 'B' union all
select 'S555', null, NULL, 'A') as ad
select * into doctor
from (
select 203 [number], 'Black' [surname], 'Peter' [firstname], 'A' [ward] union all
select 574, 'Blis', 'Mavis', 'B' union all
select 461, 'Boyne', 'Steve', 'B' union all
select 530, 'Clark', 'Nicola', 'C' union all
select 405, 'Mizzi', 'Nicola', 'A' union all
select 501, 'Mount', 'Mavis', 'A') as d
select * into ward
from (
select 'A' [code], 'Surgical' [name], 203 [consultant] union all
select 'B', 'Paediatric', 574 union all
select 'C', 'Medical', 530) as w