在SQLite中将除法校正为零

时间:2012-03-15 12:44:10

标签: sql sqlite

在我的 SQLite 语句中,如果count(t2.ref_id)为零,则会出现除零的问题。

我可以调整 SQLite 语句,这样如果count(t2.ref_id)为零,那么稀释性(稀释因子)将高于最高的非零稀释度吗?

select t1.id, cast(:totalItems as float) / count(t2.ref_id) as scarsity
from t1 left join t2 on t1.id = t2.ref_id
group by t1.id
order by scarsity

1 个答案:

答案 0 :(得分:2)

您需要检查值0并执行不同的操作。一种常见的方法是将NULL除以NULLIF()NULL来将值转换为select t1.id, cast(:totalItems as float) / NULLIF(count(t2.ref_id), 0) as scarsity from t1 left join t2 on t1.id = t2.ref_id group by t1.id order by scarsity

NULLIF()

但我不确定SQLite是否有CASE,所以你可以使用更长的select t1.id, cast(:totalItems as float) / CASE WHEN count(t2.ref_id) = 0 THEN NULL ELSE count(t2.ref_id) END as scarsity from t1 left join t2 on t1.id = t2.ref_id group by t1.id order by scarsity 版本来代替......

COUNT()

即使您输入两次,select t1.id, CASE WHEN count(t2.ref_id) = 0 THEN 9999999 ELSE cast(:totalItems as float) / count(t2.ref_id) END as scarsity from t1 left join t2 on t1.id = t2.ref_id group by t1.id order by scarsity 也不会被计算两次。该值将被重用:)

或者,如果你得到0行,做一些完全不同的事情......

{{1}}

然后你可以检查NULL是最高值,还是只检查9999999等等。