我试图从统计表中获得每位客户最后一天的最后一条记录。 我想选择最后一天销售量最大的顾客。从所有客户中选择Rails中的最后一条记录
统计信息每小时生成一次,因此客户有多个统计信息,但我只需要最后一个统计信息。
我尝试了几个命令,我只是收到错误。
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
是与勇气的最佳解决方案?或者我应该创建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:统计数据 - 统计belongs_to的:客户
可否请您添加模型声明? 为了使你的第一个查询工作,你应该加入。所以第二。 – marmeladze
你的'Customer'和'Statistic'模型之间有'has_many'' belongs_to'关系吗? – sa77
对。客户has_many:统计和统计belongs_to:客户 –