每天仅获得一条记录

时间:2019-02-04 23:40:37

标签: ruby-on-rails postgresql activerecord

我有一个Currency表,我想用1周内的日期值捕获所有值。我做了这个查询并设法得到结果:

Currency.where (date: (1.week.ago..Date.today.end_of_day)

此日期字段是日期时间。

我现在只想获取当天记录的最高日期的记录。也就是说,我要获取7条记录(一周中的每一天一次),而该记录是该特定日期的最后一条记录(日期列中的最大值)。

如何在活动记录中进行此查询?

我尝试使用date_trunc,但未成功。我的数据库是PostgreSQL

表的DLL:

货币(id:整数,currency_kind:整数,值:float,日期:datetime,created_at:datetime,updated_at:datetime)

class CreateCurrencies < ActiveRecord::Migration[5.2]
  def change
    create_table :currencies do |t|
      t.integer :currency_kind
      t.float :value
      t.datetime :date

      t.timestamps
    end
  end
end

Currency.all示例

=> #<ActiveRecord::Relation [#<Currency id: 51, currency_kind: "eur", value: 4.18835, date: "2019-02-04 05:37:59", created_at: "2019-02-04 03:08:08", updated_at: "2019-02-04 03:08:08">, #<Currency id: 52, currency_kind: "usd", value: 3.6593, date: "2019-02-04 05:37:59", created_at: "2019-02-04 03:08:08", updated_at: "2019-02-04 03:08:08">, #<Currency id: 53, currency_kind: "aud", value: 2.65061, date: "2019-02-04 05:37:59", created_at: "2019-02-04 03:08:08", updated_at: "2019-02-04 03:08:08">, #<Currency id: 54, currency_kind: "eur", value: 4.18755, date: "2019-02-04 02:47:58", created_at: "2019-02-04 03:18:13", updated_at: "2019-02-04 03:18:13">, #<Currency id: 55, currency_kind: "usd", value: 3.6593, date: "2019-02-04 02:47:59", created_at: "2019-02-04 03:18:13", updated_at: "2019-02-04 03:18:13">, #<Currency id: 56, currency_kind: "aud", value: 2.6497, date: "2019-02-04 02:47:59", created_at: "2019-02-04 03:18:13", updated_at: "2019-02-04 03:18:13">, #<Currency id: 57, currency_kind: "eur", value: 4.19655, date: "2019-02-04 22:55:59", created_at: "2019-02-04 23:26:40", updated_at: "2019-02-04 23:26:40">, #<Currency id: 58, currency_kind: "usd", value: 3.6692, date: "2019-02-04 22:55:59", created_at: "2019-02-04 23:26:40", updated_at: "2019-02-04 23:26:40">, #<Currency id: 59, currency_kind: "aud", value: 2.6499, date: "2019-02-04 22:55:59", created_at: "2019-02-04 23:26:40", updated_at: "2019-02-04 23:26:40">, #<Currency id: 60, currency_kind: "eur", value: 4.1943, date: "2019-02-04 23:27:02", created_at: "2019-02-04 23:27:09", updated_at: "2019-02-04 23:27:09">, ...]>

1 个答案:

答案 0 :(得分:0)

您需要这样的东西

Currency.select("rate, MAX(DATE_FORMAT(date, '%Y-%m')) as max_date").where(date: 1.week.ago..Date.today.end_of_day).group("DATE_FORMAT(date, '%Y-%m')")