我有一个表,允许用户存储设备
的不同指标。 devices
可以是不同的类型(想想 IoT)并且具有不同的指标。
例如车队跟踪设备可能具有速度
、distanceTravelled
、tripDuration
,而农业传感器可能具有温度
、湿度
。
请注意,单个 Assets 中的指标数量不一定相同。例如tripDuration
可能每天只更新几次,而 speed
可能每分钟更新两次。
create table metric_history
(
device_id uuid not null,
timestamp timestamp,
metric_name text,
value double precision
);
我目前正在开发一个允许用户在他们的设备上运行自定义历史报告的系统。这些报告是汇总报告。
例如,车队跟踪客户可能希望创建一份报告,显示他的每台设备在本周的情况:
- 最大速度:
MAX(speed)
- 平均速度:
AVG(speed)
- 旅行次数:
COUNT(tripDuration)
- 平均行程长度:
AVG(tripDuration)
- 等等
我将如何去查询这样的东西(希望效率更高)?努力想出一种方法来解决它。
最佳答案
使用 FILTER
clause ,例如:
select
device_id,
max(value) filter (where metric_name = 'speed') as max_speed,
avg(value) filter (where metric_name = 'speed') as avg_speed,
count(value) filter (where metric_name = 'tripDuration') as number_of_trips
from metric_history
group by device_id
关于postgresql - Postgres - 基于列值的不同聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58741022/