如何从计数中选择最大值?

时间:2016-11-09 18:41:45

标签: mysql

我试图选择具有最高专辑编号的乐队,因为它显示错误

  

未知栏' N_Albums'在'字段列表'

为了看到乐队的名字及其专辑号码,我该怎么做?

select Name, max(N_Abums) as `Albums`  
from (select a.Name, count(b.CodDisc) as `Nr`
    from `S8.Band` a join `S8.Album` b
    where a.CodBand = b.CodBand
    group by a.CodBand) as Test

3 个答案:

答案 0 :(得分:0)

相应地订购结果并仅采用第一条记录

select a.Name, count(b.CodDisc) as `Nr` 
from S8.Band a 
join S8.Album b on a.CodBand = b.CodBand 
group by a.CodBand, a.Name
order by count(b.CodDisc) desc
limit 1

答案 1 :(得分:0)

无需MAX,只需ORDER BY <COLUMN> DESC并获取第一行。

答案 2 :(得分:0)

N_Albums更改为Nr

您使用Nr将计数别名,这样您就必须使用max()。

select Name, max(Nr) as Albums
from (
    select a.Name, count(b.CodDisc) as Nr
    from S8.Band a
    join S8.Album b on a.CodBand = b.CodBand
    group by a.CodBand
) as Test

我还改进了你的连接语法并删除了所有反引号,因为它们是不必要的。