我想在从数据库查询数据以创建图形时减去两个值。但它总是返回null当我尝试代码总和在Rails中返回空值
downtime = Ticket.by_month.where(:sla => true).sum("restore_time - start_time")
我想在从数据库查询数据以创建图形时减去两个值。但它总是返回null当我尝试代码总和在Rails中返回空值
downtime = Ticket.by_month.where(:sla => true).sum("restore_time - start_time")
你有restore_time
或start_time
null
值。在SQL中,null - X
和X - null
为null
,全部为X
,null + X
和X + null
。这意味着您的任何restore_time
或start_time
列中的null
值都会将整个金额转换为null
。
您可以用null
小号忽略行:
Ticket.by_month
.where(:sla => true)
.where.not(:restore_time => nil)
.where.not(:start_time => nil)
.sum('restore_time - start_time')
或将其转换为一些有意义您的背景:
Ticket.by_month
.where(:sla => true)
.sum('coalesce(restore_time, something_sensible) - coalesce(start_time, something_sensible)')
或者是:
Ticket.by_month
.where(:sla => true)
.sum('coalesce(restore_time - start_time, something_sensible)')
在哪里something_sensible
将是你想用来代替null
s,这个值当然必须与3210调用的第一个参数具有相同的类型。
这个怎么样?
restore_time = Ticket.by_month.where(:sla => true).sum("restore_time")
start_time = Ticket.by_month.where(:sla => true).sum("start_time")
downtime = restore_time - start_time
可悲的是数据返回一个值不是多个数据,按月分组 – alfitra
非常感谢,你拯救我的一天的人 – alfitra