2011-08-11 108 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;