Reputation: 1071
I want a query that gets the difference between the max and min values grouped by day. My attempt does not work:
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`);
Each sub_meter has a value that might be >3000, but only differs by < 10 per day. I want the difference, ie a result <10. With the query above I get results >3000.
This query below, just selects one meter, and give the correct results, the max (17531), the min (17523), and the difference (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)
But adding another meter into the in clause, give a bad result, the max is 17531, and the min is 3021, the diff is 14510. But I want the diff for each meter, then summed together.
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)
Another attempt I've tried is:
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'
Upvotes: 5
Views: 37202
Reputation: 5389
The query is only grouping by day (date), but you want to group also by meter, so you need to add that into your 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`);
Then if you want to sum the differences by day you can do:
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
Or if you want to sum by meter:
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
Upvotes: 7