I have a table that allows users to stores different metrics for devices. devices can be different types (think IoT) and have different metrics.
e.g. a fleet tracking device might have speed, distanceTravelled, tripDuration whilst agricultural sensor might have temperature, humidity.
Note that there isn't necessarily the same amount of metrics within a single asset. e.g. tripDuration might only be updated a handful of times per day whereas speed could be updated twice a minute.
create table metric_history
(
device_id uuid not null,
timestamp timestamp,
metric_name text,
value double precision
);
I'm currently working on a system to allow users to run custom historical reports on their devices. These reports are aggregate reports.
For example, a fleet tracking customer might want to create a report showing for each of his devices for the current week:
- Max Speed:
MAX(speed) - Average Speed:
AVG(speed) - Number of Trips:
COUNT(tripDuration) - Average Trip Length:
AVG(tripDuration) - etc
How will I go about querying something like this (hopefully somewhat efficiently)? Struggling to come up with a way to approach it.
SELECT device_id, whatever_aggreate(value) FROM metric_history WHERE metric_name = '…' GROUP BY device_id?