如何将“分组依据”和最大值用于内连接查询?

时间:2014-02-06 16:20:51

标签: mysql

我遵循了从3个表中获取数据的查询:index_datadata_binmetrics

SELECT 
    index_data.host_name,        
    data_bin.value
FROM
    metrics 
INNER JOIN
    index_data ON index_data.id = metrics.index_id 
INNER JOIN
    data_bin ON data_bin.id_metric = metrics.metric_id 
WHERE
    metrics.metric_name = 'avg';

结果如下:

host_name      |  value
================================  
namenode1           1.125
namenode1           1
namenode1           1
namenode1           1
namenode1           1
namenode1           4.875
namenode1           1
namenode1           0.875
Centreon-Server     2
Centreon-Server     1
Centreon-Server     2
Centreon-Server     1
Centreon-Server     5
Centreon-Server     1
Centreon-Server     1
Centreon-Server     2

我的目标是每host_name只获得一条记录,最多value

所以预期的输出应为:

 namenode1          4.875
 Centreon-Server    5

我怎样才能做到这一点?

谢谢,

1 个答案:

答案 0 :(得分:1)

我认为下面会帮助你

SELECT 
     index_data.host_name,        
     Max(data_bin.value) as value
        FROM metrics 
     inner join index_data ON index_data.id = metrics.index_id 
     inner join data_bin   ON data_bin.id_metric = metrics.metric_id 

where metrics.metric_name = 'avg' AND  
FROM_UNIXTIME(data_bin.ctime) between date('2014-02-05 16:15:24') and date('2014-02-06 16:15:24') 
Group by index_data.host_name;