I’m trying to use an alias created in a SELECT in a WHERE statement. It doesn’t work and I read why in another SO question.
How do I make this work without repeating the subquery?
SELECT p.PatientID, p.PatientType, p.AccountNumber,
p.FirstName + ' ' + p.LastName PatientFullName,
p.CreatedDate, DATEDIFF(hour, p.CreatedDate, GETDATE()) TotalTime,
(SELECT AVG(BGValue)
FROM BloodGlucose
WHERE PatientID = p.PatientID) AvgBG
FROM Patients p
WHERE AvgBG > 60;
This works:
SELECT p.PatientID, p.PatientType, p.AccountNumber,
p.FirstName + ' ' + p.LastName PatientFullName, p.CreatedDate,
DATEDIFF(hour, p.CreatedDate, GETDATE()) TotalTime,
(SELECT AVG(BGValue) FROM BloodGlucose WHERE PatientID = p.PatientID) AvgBG
FROM Patients p
WHERE (SELECT AVG(BGValue) FROM BloodGlucose WHERE PatientID = p.PatientID) > 60;
But I don’t want to repeat that subquery. And I suspect it has poor performance.
Try using a derived table instead.
Derived tables work in sets and correlated subqueries work row-by-agonizing-row, that is why mine is faster.