2012-02-09 60 views
0

我有這個疑問:找到一個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 

我怎麼能找到的最大TotalPerDay不改變電流輸出通過使用PHP或更改查詢。

我試圖做到這一點,它的工作原理

$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 
+0

'選擇MAX(TotalPerDay)從myTable的其中1 = 1組由date' – 2012-02-09 12:14:06

+0

嘗試這樣做,沒有工作:'(選擇最大(COUNT(*))從numrequest其中id_re_usr = 「U1」 組(時間),DAYOFYEAR(時間)),作爲最大值' – 2012-02-09 12:24:17

+0

'從numrequest中選擇max(count(*)),其中id_re_usr =「u1」group by id_re_usr,year(time),DAYOFYEAR – 2012-02-09 12:40:43

回答

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 
相關問題