【问题标题】:How to get average of the last values by each table from database如何从数据库中获取每个表的最后一个值的平均值
【发布时间】:2021-10-07 09:23:28
【问题描述】:

我有 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, primary_key: :station_id, 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

【问题讨论】:

  • 您使用的是什么 Rails 版本?以及什么关系型数据库
  • stackoverflow.com/questions/31879150/… ... 但是使用maximum 而不是计数,那么您应该能够将总和除以大小...?

标签: sql ruby-on-rails ruby


【解决方案1】:

首先是一个小风格的评论...模型应该是Sensor,属性为value,而不是SensorValue,属性为value

此查询为您提供所需的内容,它并非完全用 sql 编写,但它会生成一个 sql 查询,如果您愿意,可以查看并使用它。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多