简体   繁体   English

Mysql-聚合function查询分组问题

[英]Mysql- Aggregate function query grouping problem

Consider following table.考虑下表。


在此处输入图像描述


I'm trying to write a query to display - Max values for all the parts per category.我正在尝试编写一个查询来显示 - 每个类别的所有部分的最大值。 Also display the date when the value was max.还显示值为最大值的日期。

So i tried this -所以我尝试了这个-

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

First of all, mysql didn't throw an error for not having Time_Captured in group by.首先,mysql 没有因为没有 Time_Captured 分组而引发错误。 Not sure if its a problem with mysql or my mysql.不确定是 mysql 还是我的mysql 的问题。

So I assume it should return -所以我认为它应该返回 -

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

But its returning me the time captured from the first record of the data set ie 11-08-2011 07:00但是它返回了我从数据集的第一条记录中捕获的时间,即11-08-2011 07:00

Not sure where I'm going wrong.不知道我哪里错了。 Any thoughts?有什么想法吗?

(Note: I'm running this inside a VM. Just in case if it changes anything) (注意:我在虚拟机中运行它。以防万一它改变了什么)

You need to join to the results of a query that finds the max(value), like this:您需要加入找到最大值(值)的查询结果,如下所示:

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';

Note that this will return multiple rows if there are multiple rows with the same max value.请注意,如果有多行具有相同的最大值,这将返回多行。

If you want to limit this to one row even though there are multiple matches for max(value), select the max(Time_Captured) (or min(Time_Captured) if you prefer), like this:如果您想将其限制为一行,即使 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