MySQL在选择行的最大值和最小值之间得到差异

时间:2012-10-19 04:12:09

标签: mysql max min

我想要一个查询来获取按天分组的最大值和最小值之间的差异。我的尝试不起作用:

SELECT date(`date`), 
   (max(value) - min(value)) as value,
FROM `sub_meter_data` 
where date(sub_meter_data.date) > '2012-10-01' 
  and sub_meterID in('58984','58985','58986','58987')
group by date(`date`);

每个sub_meter的值可能大于3000,但仅相差<每天10个。我想要差异,即结果< 10。通过上面的查询,我得到了结果> 3000。

下面的查询,只选择一个仪表,并给出正确的结果,最大值(17531),最小值(17523)和差值(8)。

SELECT date(sub_meter_data.date) as date,
   max(value) as max_meter,
   min(value) as min_meter, 
   max(value) - min(value) as diff,
FROM `sub_meter_data`
where date(sub_meter_data.date) > '2012-10-01' 
  and sub_meterID in('57636')
  group by date(sub_meter_data.date)

但是在in子句中添加另一个仪表,给出一个不好的结果,最大值是17531,最小值是3021,差值是14510.但是我想要每米的差值,然后加在一起。

SELECT date(sub_meter_data.date) as date,
   max(value) as max_meter,
   min(value) as min_meter, 
   max(value) - min(value) as diff,
   FROM `sub_meter_data`
where date(sub_meter_data.date) > '2012-10-01' 
  and sub_meterID in('57636', '57628')
  group by date(sub_meter_data.date)

我尝试过的另一种尝试是:

SELECT date(sub_meter_data.date) as date,
   sum(CASE WHEN sub_meterID = '57628' OR sub_meterID = '57636' THEN (max(value) -     min(value)) ELSE 0 END) as value
   FROM `sub_meter_data`
where date(sub_meter_data.date) > '2012-10-01' 

1 个答案:

答案 0 :(得分:5)

查询仅按天(日期)进行分组,但您还要按米进行分组,因此您需要将其添加到group by

select sub_meterID, date(`date`) as day, max(value) - min(value) as value
from `sub_meter_data`
where date(`date`) > '2012-10-01'
    and sub_meterID in ('58984','58985','58986','58987')
group by sub_meterID, date(`date`);

然后,如果你想按天加总差异,你可以这样做:

select day, sum(diff) as total_diff
from (
    select sub_meterID, date(`date`) as day, max(value) - min(value) as diff
    from `sub_meter_data`
    where date(`date`) > '2012-10-01'
       and sub_meterID in ('58984','58985','58986','58987')
    group by sub_meterID, date(`date`)
    ) a
group by day

或者如果你想按米计算:

select sub_meterID, sum(diff) as total_diff
from (
    select sub_meterID, date(`date`) as day, max(value) - min(value) as diff
    from `sub_meter_data`
    where date(`date`) > '2012-10-01'
       and sub_meterID in ('58984','58985','58986','58987')
    group by sub_meterID, date(`date`)
    ) a
group by sub_meterID