如何从数据库中获取每个表的最后一个值的平均值

我有 2 个模型:一个 stationsensor_value,它们与站 ID 相关。

class Station < ApplicationRecord
  has_many :sensor_values,primary_key: :station_id,foreign_key: :station_id,dependent: :destroy
  validates :station_id,presence: true,uniqueness: true
end
class SensorValue < ApplicationRecord
  belongs_to :station,foreign_key: :station_id
  validates :value,:type,:station_id,presence: true
end

一个 station 可以有多个 sensor values,每个 sensor values 保存不同类型的值(温度、湿度、光照)。

我需要获取每个站点所有最新指标的平均值。我当前的解决方案是获取所有站点的平均温度:

def last_sensors_values
  temperature = []

  Station.all.each do |st|
    next if st.sensor_values.empty?

    temperature_val = st.sensor_values.where(type: 'temperature').last.value
    temperature.push(temperature_val) unless temperature_val.zero?
  end

  {
    temperature: temperature.sum / temperature.size
  }
end

但我认为它可以用 SQL 来完成,关于如何改进此代码的任何想法?

感谢您的帮助)

更新: 导轨 5.2.5 数据库 PostgreSQL >= 10

wenzhubin 回答:如何从数据库中获取每个表的最后一个值的平均值

首先是一个小的样式注释...模型应该是带有 Sensor 属性的 value,而不是带有 SensorValue 属性的 value

这个查询给了你你需要的东西,它不是完全用 sql 编写的,但它会生成一个 sql 查询,如果你喜欢的话,你可以查看和使用它。

Station.joins(:sensors).select("avg(sensors.value) as avg_val").group("sensors.station_id")

返回的每个 Station 模型都有一个 #avg_val 方法,其中包含您要查找的计算。当然,您可以添加一个 where 子句来限制温度传感器。

本文链接:https://www.f2er.com/432.html

大家都在问