2011-08-11 85 views
0

請考慮下表。Mysql-聚合函數查詢分組問題


enter image description here


我想寫一個查詢,顯示 - 最大值爲每類別中的所有部件。同時顯示值爲最大值的日期。

所以我想這一點 -

select Part_id, Category, max(Value), Time_Captured 
from data_table 
where category = 'Temperature' 
group by Part_id, Category 

首先,MySQL並沒有拋出錯誤沒有Time_Captured在GROUP BY。 不知道如果它的問題與mysql或我的 MySQL。

所以,我認爲它應該返回 -

1 Temperature 50 11-08-2011 08:00 
2 Temperature 70 11-08-2011 09:00 

但其返回我的設置即11-08-2011 07:00

不知道我要去哪裏錯了數據的第一條記錄拍攝的時間。有什麼想法嗎?

(注:我在VM內運行此萬一如果它改變任何東西。)

回答

1

你需要加入到找到最大(值)查詢的結果,就像這樣:

select dt.Part_id, dt.Category, dt.Value, dt.Time_Captured 
from data_table dt 
join (select Part_id, Category, max(Value) as Value 
      from data_table group by 1, 2) x 
    on x.Part_id = dt.Part_id and x.Category = dt.Category 
where dt.category = 'Temperature'; 

請注意,如果存在具有相同最大值的多行,這將返回多行。

如果你想這個限制,即使有對最大(值)多個匹配一行,選擇MAX(Time_Captured)(或分鐘(Time_Captured)如果你願意),像這樣:

select dt.Part_id, dt.Category, dt.Value, max(dt.Time_Captured) as Time_Captured 
from data_table dt 
join (select Part_id, Category, max(Value) as Value 
      from data_table group by 1, 2) x 
    on x.Part_id = dt.Part_id and x.Category = dt.Category 
where dt.category = 'Temperature' 
group by 1, 2, 3;