我想要显示最高的号码。的剧集

时间:2016-08-11 06:58:10

标签: mysql sql join group-by sql-order-by

我有以下代码

SELECT PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME, 
COUNT(EPISODES.PRESENTERID) AS "no. of episodes"
FROM EPISODES
JOIN PRESENTERS
ON EPISODES.PRESENTERID=PRESENTERS.PRESENTERID
GROUP BY PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME
ORDER BY COUNT(EPISODES.PRESENTERID)

these are the results

我尝试添加

HAVING COUNT(EPISODES.PRESENTERID) > 2 

These are the results

但是我必须假装没有看到多少没有。有一集是在那里。还有其他方式我可以显示更多没有的行。一集?

5 个答案:

答案 0 :(得分:2)

如果您只想要具有最多剧集数量的行,您可以在查询结尾添加此项(并移除HAVING,这是无用的):

ORDER BY `no. of episodes` DESC
LIMIT 1

这个想法:你对行进行排序,使得剧集最多的记录位于顶部,然后将结果限制为一定数量(此处为1)。

您错过的是DESC关键字,因为默认情况下按排序从低到高(ASC,升序)。

答案 1 :(得分:2)

    select top 1 PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME,COUNT(EPISODES.PRESENTERID) AS "no. of episodes" FROM EPISODES JOIN PRESENTERS ON EPISODES.PRESENTERID=PRESENTERS.PRESENTERID GROUP BY PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME ORDER BY COUNT(EPISODES.PRESENTERID) desc;

答案 2 :(得分:1)

您不需要having,只需要order by COUNT(EPISODES.PRESENTERID) DESC,这应该会让您从高到低

答案 3 :(得分:0)

默认情况下,MySQL按升序对行进行排序。你需要明确告诉它按降序排序。

SELECT PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME, 
COUNT(EPISODES.PRESENTERID) AS "no. of episodes"
FROM EPISODES
JOIN PRESENTERS
ON EPISODES.PRESENTERID=PRESENTERS.PRESENTERID
GROUP BY PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME
ORDER BY COUNT(EPISODES.PRESENTERID) DESC;

上面会为您提供降序或下降的所有行,但如果您只想要一行episodes最多的行,则可以limit 1

SELECT PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME, 
COUNT(EPISODES.PRESENTERID) AS "no. of episodes"
FROM EPISODES
JOIN PRESENTERS
ON EPISODES.PRESENTERID=PRESENTERS.PRESENTERID
GROUP BY PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME
ORDER BY COUNT(EPISODES.PRESENTERID) DESC LIMIT 1;

答案 4 :(得分:0)

只需将DESC附加到您当前的查询中即可!

SELECT        PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME, COUNT(EPISODES.PRESENTERID) AS [no. of episodes]
FROM            EPISODES INNER JOIN
                         PRESENTERS ON EPISODES.PRESENTERID = PRESENTERS.PRESENTERID
GROUP BY PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME
ORDER BY [no. of episodes] DESC

期望的输出:

enter image description here

选择Top 1:

SELECT        TOP (1) PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME, COUNT(EPISODES.PRESENTERID) AS [no. of episodes]
FROM            EPISODES INNER JOIN
                         PRESENTERS ON EPISODES.PRESENTERID = PRESENTERS.PRESENTERID
GROUP BY PRESENTERS.PNRFNAME, PRESENTERS.PNRLNAME
ORDER BY [no. of episodes] DESC