无法计算排除 sqlite3 中 .each 块中当前观察值的平均值

我有以下方法。我的代码if statement在我的.each出现错误:nil can't be coerced into Float (TypeError)

我尝试了很多变体,都在.each块中。

代码应计算所有项目的平均值,按 分组Type不包括当前观察例如,在 下有 10 个不同值的 10 个项目Type foo项目 1 有一个单元格计算 9 个项目的平均值 -不包括它自己。请指教。我已经无计可施了。

下面的代码是我的 IDE 中存在的方法。 Ruby 2.3.7

specific_row[0]应该属于Id并且specific_row[1]应该属于Amount注意:我已经选择了使用.executeover.execute2的努力而不是标题数据的行程。

def billavgx(info_hash)
    begin
        db = SQLite3::Database.open('billinfo.db')
        db.results_as_hash = true
        db.transaction
        specific_amt =  db.prepare "SELECT Amount AND Id FROM bills WHERE Type = :Type" 
        specific_amt.execute info_hash[:category]
        specific_amt.each do |specific_row|
            if @total_rows == 1
                @avgx = (@total_amt - specific_row[1]) / @total_rows
            elsif @total_rows > 1
                @avgx = (@total_amt - specific_row[1]) / (@total_rows - 1)
            else
                return "insufficient entries"
            end         
            db.execute2 "UPDATE bills SET AvgX = :AvgX WHERE Id = :Id AND Type = :Type", @avgx, specific_row[0], info_hash[:category]
            end
        puts db.changes.to_s + " changes made"
        db.commit
    rescue SQLite3::Exception => e
        puts "error here " , e
    ensure
        specific_amt.close if specific_amt
        db.close if db
    end
end

上述.each块的一个主要问题是使用instance variable. 交换@avgxlocal variable avgx解决了这个问题。avgx然后可以在 SQLUPDATE语句中使用。

其次specific_row array需要指定正确的值。在这种情况下,所需的值为Amount因为arrays是 0 索引,所以值Amount存储在“specific_row[0]”中。

        specific_amt.each do |specific_row|
            if @total_rows == 1
                avgx = @total_amt / @total_rows
            elsif @total_rows > 1
                avgx = (@total_amt - specific_row[0]) / (@total_rows - 1)
            else
                puts "insufficient entries"
                return "insufficient entries"
            end 
        db.execute2 "UPDATE bills SET AvgX = :AvgX WHERE Amount = :Amount AND Type = :Type AND Year = :Year", avgx, specific_row[0], info_hash[:category], info_hash[:year]
        end

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章