我有以下表达式:
@last_report = @all_reports.where(reporting_date: Report.select('MAX(reporting_date)'))
.order(probability: :desc)
.group(:probability, :reporting_date)
.select("probability,
SUM(proposals) AS proposals,
SUM(amount) AS amount,
SUM(amount_tp) AS amount_tp")
某些记录中的字段amount_tp
可能为空。在这种情况下,它必须由amount
替换。
我怎样才能做到这一点?
答案 0 :(得分:1)
Sql的COALESCE
可能是您正在寻找的功能。这里是PostgreSQL的tutorial
用法如下:COALESCE(value,...)
,因此该函数返回第一个非NULL值:
@last_report = @all_reports.where(reporting_date: Report.select('MAX(reporting_date)'))
.order(probability: :desc)
.group(:probability, :reporting_date)
.select("probability,
SUM(proposals) AS proposals,
SUM(amount) AS amount,
SUM(COALESCE(amount_tp, amount)) AS amount_tp")
答案 1 :(得分:0)
这绝对是一种更简洁的方式,但在计算之前尝试:
@last_report.each { |x| (x.update_attributes(amount_tp: x.amount) if x.amount_tp.nil? }
这将遍历每个报告,如果amount_tp为nil,则为其指定x.amount为的值。然后执行上面的方法,每当amount_tp属性为nil时,它现在将等于amount属性