简体   繁体   English

在Ruby on Rails中减去数据表的2个字段

[英]Subtract 2 fields of a data table in Ruby on Rails

I have the following problem. 我有以下问题。

I have a table lets call it Activity. 我有一张桌子叫Activity。

In this table there are 3 fields one is the date_start , the second is date_end and the third is the activity_type , which correspond the date that the activity start and ends and the type of activity for example physical activity and eating. 在此表中,有3个字段,一个是date_start ,第二个是date_end ,第三个是activity_type ,它们对应于活动开始和结束的日期以及活动的类型,例如身体活动和饮食。

I would like to find the median time period that a activity_type lasts. 我想找到一个activity_type持续的中间时间段。

For example: 例如:

Activity.where(activity_type: "Eating healthy")

So I want to apply in this question, a sum statement with the time difference between the date_start and date_end . 所以我想在这个问题中应用一个sum语句,其中date_startdate_end之间的时间差。

How I can find the time differences of all the same type activities? 如何找到所有相同类型活动的时差?

You can use SQL's DATEDIFF function to find the number of days between each date value. 您可以使用SQL的DATEDIFF函数查找每个日期值之间的天数。 You can then use ActiveRecord 's average method to find out the median/average number of days. 然后,您可以使用ActiveRecordaverage方法找出中位数/平均天数。

condition = {activity_type: "Eating healthy"}
sql_string = "DATEDIFF(day, date_end, date_start)"
Activity.where(condition).average(sql_string) #=> numeric value

You can get the data for all activity types by grouping the rows, like so: 您可以通过对行进行分组来获取所有活动类型的数据,如下所示:

Activity.group(:activity_type).average(sql_string) #=> Hash with numeric values

But this also depends on which database you're using. 但这还取决于您使用的数据库。 For example, the DATEDIFF function doesn't exist for SQLite. 例如,SQLite不存在DATEDIFF函数。 You will have to lookup the appropriate date-difference function that you can use for your database. 您将必须查找可用于数据库的适当的日期差函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM