【发布时间】:2017-04-11 21:43:10
【问题描述】:
我试图从统计表中获取每个客户最后一天的最后一条记录。 我想选择最后一天销量最高的客户。
统计信息每小时生成一次,因此有来自客户的多个统计信息,但我只需要最后一个。
我尝试了几个命令,但都收到错误。
Statistic.where("created_at < ?",1.day.ago).select(:customer_id).distinct.order(created_at: :desc)
或
Statistic.where("created_at < ?",1.day.ago).select(:customer_id).distinct.last
pluck 是最好的解决方案吗?还是我应该创建 2 个选择? 我不知道应该把“sold_items”放在哪里。
这也可能是一个解决方案,但我不确定。
Customer.all.each do |customer|
stats = customer.statistics.where("created_at < ?",Date.today).last
count = stats.sold_items if stats.sold_items > count
best = customer if count = stats.sold_items
end
模型: 客户 has_many :statistics - 统计数据 belongs_to :customer
【问题讨论】:
-
能否请您添加模型声明?为了使您的第一个查询起作用,您应该进行联接。所以第二个。
-
您的
Customer和Statistic模型之间是否存在has_manybelongs_to关系? -
对。客户 has_many :statistics 和 Statistic belongs_to :customer
标签: ruby-on-rails select distinct