Create Table hospital
(
Id INT Identity(1,1),
HospitalName Varchar(50),
ExternalID INT Primary Key
)
GO
Create table Doctor
(
ID Int Identity(1,1),
Doctorname Varchar(100),
Active Char(1),
InternalID INT
)
go
ALTER TABLE Doctor ADD FOREIGN KEY (InternalID)
REFERENCES Hospital (ExternalID)
go
INSERT INTO hospital (HospitalName, ExternalID)
VALUES ('Innova', 1), ('Reston', 2), ('Fairfax', 3)
go
INSERT INTO Doctor (Doctorname, Active, InternalID)
VALUES('Nick', 'A', 1), ('Nathan', 'D', 1), ('Dean', 'D', 1), ('Rick', 'D', 2), ('Tony', 'D', 2), ('Bob', 'D', 2), ('Sugar', 'A', 3), ('Shrek', 'A', 3)
go
select * from hospital
Select * from Doctor
GO
D
代表停用 A
代表Active
在医院,如果任何1名医生处于活动状态,我希望显示Yes
N
由于我的查询性质,我不能使用CTE'
请提供任何简单的脚本
答案 0 :(得分:1)
您可以使用case
语句和exists
:
select h.*,
(case when exists (select 1
from doctor d
where d.internalid = h.externalid and d.active = 'A'
)
then 'Yes' else 'N'
end)
from hospital h;
答案 1 :(得分:0)
select h.HospitalName
, case when max(d.Id) is null then 'N' else 'Yes' end ActiveDoctorInHospital
from hospital h
left outer join doctor d
on d.InternalId = h.ExternalId
and d.Active = 'A'
group by h.id, h.HospitalName