id name gpa batch
1 jhon 2 y1
2 sandy 2.8 y2
4 kile 3 y2
5 siya 3.2 y1
我想找到最大平均gpa的批次。 所以我写了下面的代码。
select max(gpa)
from student
where gpa in (select batch,AVG(gpa)
from student
group by batch)
我通过单独执行它检查子查询,它工作正常。但主查询中有错误。
答案 0 :(得分:1)
您可以改为使用TOP
:
SELECT TOP 1 batch
FROM student
GROUP BY batch
ORDER BY AVG(gpa) DESC
使用MAX
:
SELECT *
FROM(
SELECT batch, avg_gpa = AVG(gpa)
FROM student
GROUP BY batch
) s
WHERE avg_gpa = (
SELECT MAX(avg_gpa)
FROM (
SELECT batch, avg_gpa = AVG(gpa)
FROM #student
GROUP BY batch
) t
)
答案 1 :(得分:0)
您的子查询返回2个值,主查询中的In函数正在查找1个项目。我建议从内部查询中删除批处理。
答案 2 :(得分:0)
SELECT TOP 1 batch, avg_gpa = AVG(gpa)
FROM student
GROUP BY batch
ORDER BY avg_gpa desc