本文介绍了在 WHERE 语句中使用子查询的别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用在 SELECT 中创建的别名,但在 WHERE 语句中.我知道它不起作用,我只是在另一个 SO 问题中阅读了原因.
I'm trying to use an alias created in a SELECT, but in a WHERE statement. I know it doesn't work and I just read why in another SO question.
但我的问题是:在不重复子查询的情况下,我应该采取什么其他解决方案来完成这项工作?
But my question is : what other solution should I take to 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;
我知道这行得通:
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'm pretty sure it isn't very performance-wise so that is the reason I'm asking for a better solution here.
谢谢!
推荐答案
尝试改用派生表.
SELECT p.PatientID, p.PatientType, p.AccountNumber, p.FirstName + ' ' + p.LastName PatientFullName, p.CreatedDate, DATEDIFF(hour, p.CreatedDate, GETDATE()) TotalTime, bg.AvgBG
FROM Patients p
JOIN (SELECT PatientID, AVG(BGValue) AvgBG FROM BloodGlucose group by PatientID ) BG
ON BG.PatientID = p.PatientID
WHERE AvgBG > 60;
这篇关于在 WHERE 语句中使用子查询的别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!