简体   繁体   English

在SQLite中将除法校正为零

[英]Correcting division by zero in SQLite

In my SQLite statement below there is a problem with division by zero in the case count(t2.ref_id) is zero. 在下面的SQLite语句中,在count(t2.ref_id)为零的情况下存在除零的问题。

Could I adjust the SQLite statement so that if the count(t2.ref_id) is zero the scarsity (scarsity factor) will be higher than the highest non-zero scarsity? 我可以调整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

You need to check for the value 0 and do something different. 您需要检查值0并执行不同的操作。 One common way is to divide by NULL as many SQL varieties have NULLIF() to turn a value into a NULL instead. 一种常见的方法是除以NULL因为许多SQL变量具有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

But I'm not sure that SQLite has NULLIF() , so you could use the more long winded CASE version instead... 但是我不确定SQLite是否有NULLIF() ,所以你可以使用更长的winded 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

The COUNT() won't be calculated twice even though you typed it twice. 即使您键入两次, COUNT()也不会被计算两次。 The value will be re-used :) 该值将被重用:)

Alternatively, do something completely different if you get 0 rows... 或者,如果你获得0行,做一些完全不同的事情......

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

Then you can check for NULLs as being the highest value, or just check for 9999999, etc, etc. 然后你可以检查NULL是最高值,还是只检查9999999等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM