gpt4 book ai didi

Mysql-聚合函数查询分组问题

转载 作者:行者123 更新时间:2023-11-29 14:45:36 25 4
gpt4 key购买 nike

考虑下表。

<小时/>

enter image description here

<小时/>

我正在尝试编写一个查询来显示 - 每个类别的所有零件的最大值。还显示该值达到最大值的日期。

所以我尝试了这个 -

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

首先,mysql并没有因为group by中没有Time_Captured而抛出错误。不确定是 mysql 还是 my mysql 的问题。

所以我认为它应该返回 -

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

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

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

(注意:我在虚拟机内运行它。以防万一它会改变任何内容)

最佳答案

您需要连接到查找 max(value) 的查询结果,如下所示:

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) 有多个匹配项,请选择 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;

关于Mysql-聚合函数查询分组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7020513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com