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

问题描述 投票:-3回答:1

我有以下方法。我的代码在我的if statement区块内的.each上遇到了错误:nil can't be coerced into Float (TypeError)

我尝试过很多变种,都是在.each块中遇到的。

代码应计算所有项目的平均值,按Type分组,不包括当前观察值。例如,在Type foo下有10个具有10个不同值的项目。第1项有一个单元格计算9个项目的平均值 - 不包括其自身。请指教。我很快就结束了。

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

specific_row[0]应该属于Idspecific_row[1]应该属于Amount。注意:我已经选择在.execute上使用.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
ruby sqlite each mean
1个回答
0
投票

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

第二个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
© www.soinside.com 2019 - 2024. All rights reserved.