繁体   English   中英

Mysql-聚合function查询分组问题

[英]Mysql- Aggregate function query grouping problem

考虑下表。


在此处输入图像描述


我正在尝试编写一个查询来显示 - 每个类别的所有部分的最大值。 还显示值为最大值的日期。

所以我尝试了这个-

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

首先,mysql 没有因为没有 Time_Captured 分组而引发错误。 不确定是 mysql 还是我的mysql 的问题。

所以我认为它应该返回 -

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

但是它返回了我从数据集的第一条记录中捕获的时间,即11-08-2011 07:00

不知道我哪里错了。 有什么想法吗?

(注意:我在虚拟机中运行它。以防万一它改变了什么)

您需要加入找到最大值(值)的查询结果,如下所示:

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(value) 有多个匹配项,select max(Time_Captured) (或 min(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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM