Rails / ActiveRecord DateTime的平均值返回BigDecimal

时间:2016-08-09 17:32:15

标签: ruby-on-rails activerecord sqlite

我正在编写一个结帐系统(比如库),我正在尝试计算使用Ruby on Rails检查标题的平均时间。开发数据库是SQLite3。

我调用records = Title.find(1).records.where('[in] IS NOT NULL')来获取已返回的记录的关系(在检查标题时是DateTime)。我希望能够调用average_time = records.average(:in) - records.average(:out),但这是我得到的输出(来自rails控制台)。

irb(main):023:0> average_time = records.average(:in) - records.average(:out)
   (0.3ms)  SELECT AVG("records"."in") FROM "records" WHERE "records"."title_id" = ? AND ([in] IS NOT NULL)  [["title_id", 1]]
   (0.2ms)  SELECT AVG("records"."out") FROM "records" WHERE "records"."title_id" = ? AND ([in] IS NOT NULL)  [["title_id", 1]]
=> #<BigDecimal:7fe104a4cd50,'0.0',9(18)>

我希望能够在不选择每个进出时间的情况下获取平均值,然后在实际应用中对它们进行平均。潜在的问题似乎是SQLite3只返回年份。

sqlite> SELECT AVG("records"."in") FROM "records" WHERE "records"."title_id" = 1 AND ([in] IS NOT NULL);
2016.0

sqlite> SELECT AVG("records"."in" - "records"."out") FROM "records" WHERE "records"."title_id" = 1 AND ([in] IS NOT NULL);
0.0

(架构供参考)

sqlite> .schema records
CREATE TABLE "records" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title_id" integer NOT NULL, "borrower" varchar NOT NULL, "note" text, "agent" varchar NOT NULL, "out" datetime NOT NULL, "in" datetime, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, "due" datetime, "return_approved" datetime);
CREATE INDEX "index_records_on_title_id" ON "records" ("title_id");

然而,这确实有效。

sqlite> SELECT AVG(strftime("%s", "records"."in") - strftime("%s", "records"."out")) FROM "records" WHERE "records"."title_id" = 1 AND ([in] IS NOT NULL);
91290.0

这里的解决方案是放弃DateTime格式并将所有内容表示为代表纪元时间戳的整数吗?最终,我相信生产环境将是MySQL。

0 个答案:

没有答案