开发者

Is there a more elegant way of calculating the median of a group of numbers using ruby-dbi and connection to a database

开发者 https://www.devze.com 2023-03-25 04:44 出处:网络
I have the following code which calculates the median of a group of numbers drawn from a database. The question relates to if there is an easier way for calculating the median of a column from a array

I have the following code which calculates the median of a group of numbers drawn from a database. The question relates to if there is an easier way for calculating the median of a column from a array of DBI::ROWs?

As an aside array.sort in the median calculation throws and error 'undefined method'

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.dis开发者_StackOverflow社区connect if dbh
end


Intersystems Caché has a MEDIAN function:

MEDIAN

One of the examples on that page:

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


Update

Error in array was due to nil elements in ActiveRecord set, fixed by

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

Median function only in intersystems cache deep see and not regular SQL

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号