1.弄清了初学数据库时候的一个问题。
【找出水手的平均年龄在所有等级中是最低的那些等级】
错误写法:
SELECT S.rating
FROM Sailor S
WHERE AVG(S.age)=(SELECT MIN(AVG(S2.age))
FROM Sailor S2
GROUP BY S2.rating)
以前一直被聚集函数里不能有聚集函数规定困扰,其实就算合法,选出的也和没用MIN一样的,因为是在分组里选的而不是在分组集合中选。
正确写法:(产生一个临时表)
SELECT Temp.rating,Temp.avgage
FROM(SELECT S.rating,AVG (S.age) AS avgage
FROM Sailor S
GROUP BY S.rating) AS Temp
WHERE Temp.avgage=(SELECT MIN(Temp.avgage) FROM TEMP)
即选出一个有rating和平均年龄avgage的TEMP表,再用嵌套选出min(avgage)
另外方法待测试:
SELECT Temp.rating,Temp.avgage
FROM(SELECT S.rating,AVG (S.age) AS avgage
FROM Sailor S
GROUP BY S.rating) AS Temp
WHERE Temp.avgage=(SELECT MIN(Temp.avgage) FROM TEMP)
时间: 2024-10-17 02:50:04