在不使用MAX和ORDER BY的情况下订购从高到低的值

时间:2019-05-05 17:58:54

标签: sql sql-server

我想获取使用了Count()的列的最大计数,并希望不使用maxorder by desc就将该列的最高值到最低值进行排序。

我尝试过

SELECT COUNT(subject) AS CNT, student
FROM AUTHOR
GROUP BY student AU1
WHERE not exists (SELECT * FROM AUTHOR AU2 
                  WHERE AU2.student <> AU1.student AND AU2.subject > AU1.CNT)

但是它没有返回期望的输出。

所需的输出与

相同
SELECT COUNT(subject) AS CNT, student
FROM AUTHOR
GROUP BY Student
ORDER BY CNT DESC

但是没有order by descMAX

2 个答案:

答案 0 :(得分:2)

您可以使用ORDER BY ASC

SELECT COUNT(subject) AS CNT, student
FROM AUTHOR
GROUP BY Student
ORDER BY (- CNT) ASC;

如果要按特定顺序显示结果,则需要使用ORDER BY。这是使用SQL的规则之一。

答案 1 :(得分:0)

好的,因此不允许DESC,也不允许MAX。

SELECT
    COUNT(subject) AS CNT, student
FROM
    AUTHOR
GROUP BY 
    Student
ORDER BY 
    -CNT

这不适用于每个数据库软件。 其他版本:

SELECT * FROM (
    SELECT
        COUNT(subject) AS CNT, student
    FROM
        AUTHOR
    GROUP BY 
        Student
    ) t
ORDER BY 
    -CNT