如何在SQL中使用MAX函数?

时间:2015-04-10 23:25:25

标签: sql max

这是我的疑问:

SELECT Cottage15.CNUM,Cottage15.Rent,Assignment15.Hours
FROM Cottage15
INNER JOIN Assignment15
ON Cottage15.CNUM=Assignment15.CNUM
ORDER BY Assignment15.AID;

它有效,但我无法弄清楚如何将Max功能应用于hours?我希望MAX(Assignment15.Hours)能起作用!?

此查询显示所有行,但我只希望它显示基于小时字段的数字最高的某些行。

3 个答案:

答案 0 :(得分:1)

我认为这就是你想要的

SELECT Cottage15.CNUM,Cottage15.Rent,Assignment15.Hours
FROM Cottage15
INNER JOIN Assignment15
ON Cottage15.CNUM=Assignment15.CNUM
WHERE Assignment15.Hours = (SELECT MAX(Assignment15.Hours) FROM Assignment15)
ORDER BY Assignment15.Hours

答案 1 :(得分:1)

您必须添加组聚合才能应用Max函数

 SELECT Cottage15.CNUM,Cottage15.Rent,Max(Assignment15.Hours)
 FROM Cottage15
 INNER JOIN Assignment15
 ON Cottage15.CNUM=Assignment15.CNUM
 group by Cottage15.CNUM,Cottage15.Rent
 ORDER BY Assignment15.AID;

答案 2 :(得分:0)

如果您希望每个max(hour)获得Cottage15.CNUM and Cottage15.Rent 然后使用max(Assignment15.Hours)group by Cottage15.CNUM,Cottage15.Rent

SELECT Cottage15.CNUM,Cottage15.Rent,MAX(Assignment15.Hours)
FROM Cottage15
INNER JOIN Assignment15
ON Cottage15.CNUM=Assignment15.CNUM
GROUP BY Cottage15.CNUM,Cottage15.Rent

但是如果你想让Cottage15.CNUM and Cottage15.Rent在整个结果集中有max(Assignment15.Hours),那么你可以通过以下方式获得它:

SELECT Cottage15.CNUM,Cottage15.Rent,Assignment15.Hours
FROM Cottage15
INNER JOIN Assignment15
ON Cottage15.CNUM=Assignment15.CNUM
WHERE Assignment15.Hours = ( SELECT MAX(Assignment15.Hours)
                             FROM Cottage15
                             INNER JOIN Assignment15
                             ON Cottage15.CNUM=Assignment15.CNUM
                            )