SQL无效的组功能

时间:2017-02-25 15:08:54

标签: mysql

我想选择具有最大取消行程数的列。我知道如何计算使用SQL语句的行程次数,但是,当我尝试使用max函数时,它会给出无效的组函数错误。 我的SQL语句如下:enter image description here

select t.ServiceNumber, t.RouteNumber, remark,
       max(count(if(Cancelled =1 ,1,null))) as"Total Cancelled Trip"
from trip t inner join
     route r 
     on r.ServiceNumber = t.ServiceNumber and
        r.RouteNumber = t.RouteNumber
group by t.ServiceNumber, t.RouteNumber,remark;

1 个答案:

答案 0 :(得分:0)

如果您只想要一行具有最大值,则可以执行以下操作:

select t.ServiceNumber, t.RouteNumber, remark,
       count(*) as "Total Cancelled Trip"
from trip t inner join
     route r 
     on r.ServiceNumber = t.ServiceNumber and
        r.RouteNumber = t.RouteNumber
where Cancelled = 1
group by t.ServiceNumber, t.RouteNumber, remark
order by count(*) desc
limit 1;

在MySQL中获取所有这些行是很棘手的。也许最简单的方法是使用变量:

select tr.*
from (select t.ServiceNumber, t.RouteNumber, remark,
             count(*) as "Total Cancelled Trip",
             (@maxtct = greatest(@maxtct, count(*))
      from trip t inner join
           route r 
           on r.ServiceNumber = t.ServiceNumber and
              r.RouteNumber = t.RouteNumber cross join
           (select @maxtct := 0) params
      where Cancelled = 1
      group by t.ServiceNumber, t.RouteNumber, remark
     ) tr
where `Total Cancelled Trip` = @maxtct;