SQL在没有top命令的情况下查找最大值

时间:2014-02-02 11:14:36

标签: sql sql-server

假设我有一个带桌子的基地:

-courses (key: name [ofthecourse], other attributes: year in which the course takes place)

我想完成查询以查找问题的答案:

在哪一年的学习课程数量最多?

通常,查询将是:

SELECT TOP 1 STUDYEAR 
FROM COURSES 
GROUP BY STUDYEAR 
ORDER BY COUNT(CNO) DESC;

但我的问题是,哪个查询可以在不使用TOP 1短语的情况下完成此操作?

1 个答案:

答案 0 :(得分:2)

您可以使用内部查询来获取最大数量。唯一的区别是,如果它们具有相同的计数,它可以返回多个记录。

SELECT STUDYEAR 
FROM COURSES 
GROUP BY STUDYEAR 
HAVING COUNT(CNO) = (SELECT MAX(CNOCount) FROM 
        (SELECT COUNT(CNO) CNOCount
        FROM COURSES 
        GROUP BY STUDYEAR) X) 

只有一个内部查询的另一个版本:

SELECT STUDYEAR
FROM
    (SELECT STUDYEAR, ROW_NUMBER() OVER (ORDER BY COUNT(CNO) DESC) RowNumber
    FROM COURSES 
    GROUP BY STUDYEAR) X
WHERE RowNumber = 1