简体   繁体   English

在 Rails 中查找数据库字段之间操作的平均值/最小值/最大值

[英]Find average/min/max of operation between database fields in Rails

Relatively new to SQL and ORM. SQL 和 ORM 相对较新。

Let's say I have a database table with start_at and finish_at fields (both datetime).假设我有一个包含 start_at 和 finish_at 字段(均为日期时间)的数据库表。 Table contains 10000 items for example.例如,表包含 10000 个项目。

How to calculate the average, max/min duration (finish_at - start_at) using ruby or Active Record tools?如何使用 ruby​​ 或 Active Record 工具计算平均、最大/最小持续时间 (finish_at - start_at)? There is no need to write it somewhere, just need numbers.不需要在某处写它,只需要数字。

table = MyClass.arel_table
duration = table[:finish_at] - table[:start_at]
MyClass.pick(duration.maximum, duration.minimum, duration.average)
#=> ["125 days 20:46:34.05816", "00:00:00.063579", "20 days 23:30:16.221092"]

Cast them to another data type as needed or use directly in other queries.根据需要将它们转换为另一种数据类型或直接在其他查询中使用。

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

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