sql查找最大值和与该值相等的行数

col17t5w  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(351)

给定一个表,我试图找到maxmonthshackos和具有maxmonthshackos值的id的数量。
我尝试了下面的代码,但似乎我们不能使用max子句在内部选择。

SELECT MAX(MONTHS * HACKOS) AS MAXIMUM_HACKOS,
(SELECT COUNT(ID) FROM HACKER WHERE MONTHS*HACKOS = MAX(MONTHS*HACKOS)) AS NUMBER_OF_HACKERS
FROM HACKER ;

正确的预期输出是144和2,但我的代码是错误的。

a14dhokn

a14dhokn1#

您可以使用此查询:

SELECT MAX(MONTHS * HACKOS) FROM HACKER

WHERE 条款,然后加总:

SELECT MAX(MONTHS * HACKOS) AS MAXIMUM_HACKOS,
       COUNT(*) AS NUMBER_OF_HACKERS
FROM HACKER
WHERE MONTHS * HACKOS = (SELECT MAX(MONTHS * HACKOS) FROM HACKER)
dz6r00yl

dz6r00yl2#

select     top 1
           MONTHS * HACKOS,
           count(*)
from       HACKER
group by   MONTHS * HACKOS
order by   MONTHS * HACKOS desc
mzmfm0qo

mzmfm0qo3#

这能解决你的问题吗?

SELECT ID, NAME, MAX(MAXIMUM_HACKOS) FROM ( SELECT ID, NAME, ( MONTHS * HACKOS) as MAXIMUM_HACKOS FROM HACKER) A LIMIT 1

相关问题