我有以下表达式:

@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取代。
我怎样才能做到这一点?

最佳答案

Sql的COALESCE可能是您正在寻找的函数。这是PostgreSQL的tutorial
用法如下:COALESCE(value,...),因此函数返回第一个非空值:

@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")

关于ruby-on-rails - 如果Rails中的字段为空,如何替换组/总和中的字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45797395/

10-08 22:57