我有下面的代碼來計算從數據庫中繪製的一組數字的中位數。這個問題涉及是否有一種更簡單的方法來計算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
優秀固定的,我一定是錯過了一個!謝謝 –