查找MySQL查询结果字段的最大值

时间:2012-02-09 12:08:24

标签: php mysql

我有这个查询:

        select
        id_re_usr,
        year(time) as AYear,
        DAYOFYEAR(time) as ADay,
        DATE_FORMAT(time, "%m-%d-%y") as date,
        count(*) as TotalPerDay
        from numrequest
        where id_re_usr = "u1"
        group by id_re_usr, AYear, ADay
        order by AYear, ADay

输出类似

的内容
   date      TotalPerDay 
------------------------        
01-01-87         1
01-09-12         5
02-09-12         17
03-09-12         1

如何在不使用php或更改查询来更改当前输出的情况下找到最大TotalPerDay。

我试图这样做并且有效

  $max=0;
  while($row=mysql_fetch_array($results)){
      if($max<$row['TotalPerDay']){ $max= $row['TotalPerDay'];} 
  }

但是没有直接的方法吗?

如果修改查询,则输出应为

   date      TotalPerDay        max
----------------------------------------        
01-01-87         1               17
01-09-12         5               17
02-09-12         17              17
03-09-12         1               17

1 个答案:

答案 0 :(得分:1)

将其加入到仅包含最大计数的第二个查询中。每天最内部查询(对于给定用户)每天计数的一组行数。从那以后,下一个外部执行从该集合中选择MAX()来查找并获得一个代表最高日数的记录...因为它总是返回一行,并且加入到原始的numRequest表中它将是一个笛卡尔,但没有任何问题,因为它只有一条记录,无论如何你想要在每个返回的行上都有这个值。

select
      id_re_usr,
      year(time) as AYear,
      DAYOFYEAR(time) as ADay,
      DATE_FORMAT(time, "%m-%d-%y") as date,
      count(*) as TotalPerDay,
      HighestCount.Max1 as HighestOneDayCount
   from
      numrequest,
      ( select max( CountsByDate.DayCount ) Max1
           from ( select count(*) as DayCount
                     from numrequests nr
                     where nr.id_re_usr = "u1"
                     group by date( nr.time )) CountsByDate
      ) HighestCount
   where 
      id_re_usr = "u1"
   group by 
      id_re_usr, 
      AYear, 
      ADay
   order by 
      AYear, 
      ADay