2011-08-04 42 views
1

我有下面的代碼來計算從數據庫中繪製的一組數字的中位數。這個問題涉及是否有一種更簡單的方法來計算DBI :: ROW數組中列的中位數?有沒有一種更優雅的方式來計算使用ruby-dbi和連接到數據庫的一組數字的中位數

作爲題外話的Array.sort在中值計算拋出和錯誤 '未定義的方法'

require 'dbi' 

def median(array, already_sorted=false) 
     return nil if array.empty? 
     # array.sort 
     m_pos = array.size/2 
    return array.size % 2 == 1 ? array[m_pos] : mean(array[m_pos-1..m_pos]) 
end 

def mean(array) 
    array.inject(array.inject(0) { |sum, x| sum += x }/array.size.to_f) 
end 

begin 
    dbh = DBI.connect('DBI:jdbc:Cache://10.150.98.11:1972/SQLHRT', 'tpathhrt', 'tpathhrt', 
       'driver'=>'com.intersys.jdbc.CacheDriver') 

    sth = dbh.prepare("SELECT 
     DATEDIFF('hh',Result_Set.Date_Time_Booked_In,current_timestamp) AS HrsIn 
      FROM 
     iLabTP.Outstanding_Work_Index, 
     iLabTP.Result_Set Result_Set, 
     iLabTP.Request 
      WHERE 
     Outstanding_Work_Index.Request_Row_ID = Result_Set.Request_Row_ID and 
     Outstanding_Work_Index.Request_Row_ID = Request.Request_Row_ID and 
     Result_Set.Set_Code = 'TVITDN' order by HrsIn ASC") 

    sth.execute() 

    arr =[1] 
    sth.fetch do |row| 
     arr << row[0] 
    end 

    printf "Number of Records %d:\n", arr.size 
    printf "Median %s:\n", median(arr) 

    sth.finish 

rescue DBI::DatabaseError => e 
    puts "An error occurred" 
    puts "Error code: #{e.err}" 
    puts "Error message: #{e.errstr}" 
ensure 
    # disconnect from server 
    dbh.disconnect if dbh 
end 

回答

1

InterSystems的高速緩存具有一個MEDIAN函數:

MEDIAN

其中一個上,所述實施例頁碼:

SELECT MEDIAN(birthd.decade.MEMBERS, MEASURES.[%COUNT]) ON 0 FROM patients 
+0

優秀固定的,我一定是錯過了一個!謝謝 –

0

更新

錯誤陣列是由於ActiveRecord的集零元素,通過

<%if !statistic.HrsIn.nil? %> 
    ['<%= statistic.Specimen_Number %>', <%= statistic.HrsIn %>], 
    <% end %> 

平均功能僅適用於InterSystems的緩存中看到深,而不是常規的SQL

相關問題