如何将`where`条件应用于每条记录

Posted

技术标签:

【中文标题】如何将`where`条件应用于每条记录【英文标题】:How to apply `where` condition to each record 【发布时间】:2019-04-23 15:01:23 【问题描述】:

我想为每个HPId 显示difference_in_days,它存在于表AccountClose 中。

这是我的代码

@a = AccountClose.where("AccountCloseId is not null").last.Date.to_date
@before = Date.today 
@difference_in_days = (@before.to_date - @a.to_date).to_i 

上面的查询只显示最后一条记录的difference_in_days。谁能帮我解决这个问题?

【问题讨论】:

您只获得最后一条记录的差异_in_days,因为您单独获取最后一条记录。 @a = AccountClose.where("AccountCloseId is not null").last.Date.to_date 此语句中的最后一条仅获取最后一条记录。希望它能澄清你的疑问。 你能显示AccountClose架构或表结构吗? AccountClose(AccountCloseId: integer, HPId: integer, UsersId: integer, Date: datetime) @TChaitanyaTatavolu 您可以检查下面给出的答案,这就是您标记为正确的答案之间的区别。 【参考方案1】:

旁注...

你真的应该尝试遵循 Rails 的方式。约定结束 配置。这意味着要注意如何命名数据库, 表格和字段等等。它让生活更轻松。

https://en.wikipedia.org/wiki/Ruby_on_Rails https://en.wikibooks.org/wiki/Ruby_on_Rails

【讨论】:

【参考方案2】:

使用 pluck 查询作为数组获取所有 closed_dates

@closed_dates = AccountClose.where("AccountCloseId is not null").pluck('date(Date)')

=> [2017 年 1 月 20 日星期五、2017 年 1 月 22 日星期日、2017 年 1 月 22 日星期日、2017 年 2 月 2 日星期四、2018 年 6 月 26 日星期二、2018 年 6 月 27 日星期三、2018 年 7 月 2 日星期一、星期三、 2018 年 7 月 4 日,周三,2018 年 7 月 11 日,周三,2018 年 7 月 11 日,周三,2018 年 7 月 11 日,周四,2018 年 7 月 12 日,周四,2018 年 7 月 12 日,周五,2018 年 7 月 13 日..]

显示 AccountClose 中存在的每个 HPId 的 difference_in_days

@closed_dates.each do |colsed_date|
  puts "Difference in days is #(Date.today - colsed_date).to_i"
end

【讨论】:

【参考方案3】:
@before = Date.today 
@a = AccountClose.where("AccountCloseId is not null")
@a.each_with_index|account_close,i|
   @difference_in_days = (@before.to_date - account_close.Date.to_date).to_i 
   puts "Difference in days for account close #i: \t #@difference_in_days"

【讨论】:

谢谢!!!但它向我显示了“未定义方法 to_date”之类的错误 NoMethodError (#<:relation:0x0000002ddd6760> AccountClose 中的日期列是什么? a.to_date 在这一行你需要添加 a.date_column.to_date @TChaitanyaTatavolu 如果答案仍然显示错误,您是如何接受的?大声笑 这一行出现错误。 @difference_in_days = (@before.to_date - @a.to_date).to_i

以上是关于如何将`where`条件应用于每条记录的主要内容,如果未能解决你的问题,请参考以下文章

如果是单条记录,不适用where条件;如果是多条记录,应用where条件,返回单条记录

如何将函数应用于每组数据框

Laravel 4:如何将 WHERE 条件应用于 Eloquent 类的所有查询?

如何将函数应用于每一行data.table

当我在 R 中使用聚合时,我可以将总和应用于每一行吗?

Volatility