這是一個可怕的標題。讓我澄清一下。查詢連接表,並選擇null如果條件無效
我試圖編寫一個查詢,將選擇已加入各種表的某些列。這裏的查詢是什麼樣子:
select distinct p.PAtientID, p.FirstNAme, p.LAstNAme, nrc.RiskClassification as [Risk Classification],
ptt.NExtScheduledDAte as [Toxicology Next Scheduled Date],
ppc.NextScheduledDate as [Pill Count Next Scheduled Date],
pha.NextScheduledDate as [Mental Health Assessment Next Scheduled Date],
ppr.NExtScheduledDate as [PDMP Next Scheduled Date],
pcsa.NExtScheduledDate as [CSA Next Scheduled DAte]
from Patient p, PAtientRiskClassification prc, NetworkRiskClassification nrc,
PAtientToxicologyTesting ptt, PAtientPillCount ppc, PAtientHEalthAssessment pha,
PatientPRescriptionRegistry ppr, PAtientControlledSubstanceAgreement pcsa,
Prescriber pr, NetworkPRescriber np
where p.PAtientID = prc.PAtientID
and p.PAtientID = ptt.PAtientID
and ppc.PatientID = p.PAtientID
and pha.PAtientID = p.PAtientID
and ppr.PatientID = p.PAtientID
and pcsa.PatientID = p.PAtientID
and pr.PrescriberID = np.PrescriberID
and np.NetworkPrescriberID = p.NEtworkPrescriberID
and prc.NetworkRiskClassificationID = nrc.NetworkRiskClassificationID
and pr.Display like '%Kohles Brian%'
現在我查詢的問題在於,它只會選擇對具有所有的真實條件的患者病人的名字。 我想能夠同時選擇患者,如果他們有以下條件真爲他們1:
p.PAtientID = ptt.PAtientID
and ppc.PatientID = p.PAtientID
and pha.PAtientID = p.PAtientID
and ppr.PatientID = p.PAtientID
and pcsa.PatientID = p.PAtientID
,選擇到位不驗證條件列空或空字符串。
目前,我在寫類似下面的5次獨立的查詢:
select distinct p.PatientID, p.Display as [Patient Name],
nrc.RiskClassification as Risk,
ppr.NextScheduledDate as [PDMP Next Scheduled Date] from PatientPrescriptionRegistry ppr, Patient p
cross apply
(select top(1) RiskClassification, PatientID from NetworkRiskClassification nrc, PatientRiskClassification prc
where nrc.NetworkRiskClassificationID = prc.NetworkRiskCLassificationID and PatientID = p.PatientID order by PatientRiskClassificationID desc) nrc
where p.PatientID = ppr.PatientID and
(p.NetworkPRescriberID = 44 or p.NetworkPrescriberID = 403)
order by p.PatientID
總之,我要爲每位患者顯示來自5代不同的活動表「下一步的預定活動」列其中一些人可能沒有完成所有5個活動。
我該如何做到這一點?
*從不*在'FROM'子句中使用逗號。 *總是*使用正確的,明確的'JOIN'語法。 –
有什麼理由嗎? –
是的,有許多理由不使用隱式聯接的舊的過時的語法。其中最常見的一種是,通過忘記加入條款,你不太可能犯錯誤。第二個是你的查詢更易於閱讀,理解和維護。第三個是它有助於理解和解決你目前擁有的問題。 – oerkelens