SQLite 中的 CEIL 和 FLOOR

CEIL and FLOOR in SQLite

SQLite[=16= 中查找数字的 cielfloor 最干净的方法是什么]?不幸的是,SQLite 只有 ROUND() 函数。

公式

上限: cast ( x as int ) + ( x > cast ( x as int ))
取x的整数部分,小数大于0则加1

楼层: cast ( x as int ) - ( x < cast ( x as int ))
取x的整数部分,小数小于0则减1


例子

上限:
SELECT (cast ( amount as int ) + ( amount > cast ( amount as int ))) AS amount FROM SALES WHERE id = 128;
楼层:
SELECT (cast ( amount as int ) - ( amount < cast ( amount as int ))) AS amount FROM SALES WHERE id = 128;



我已经用 MySQL ceil()floor() 函数检查了所有极端情况,包括负数。

你可以用ROUND()达到CEILFLOOR的效果,如果你手头的数字加减0.5。我更喜欢这个,因为它可以更具可读性。

扩展 Anees 的示例:

上限 : SELECT ROUND(amount+0.5, 0) AS amount FROM SALES WHERE id = 128;
楼层SELECT ROUND(amount-0.5, 0) AS amount FROM SALES WHERE id = 128;

感谢 Anees 在下面发表评论,我也没有想到那个极端情况。他的解决方案更稳健。

https://www.sqlite.org/lang_mathfunc.html#ceil

显然 SQLite 确实提供了上限:

ceil(X)
ceiling(X)

Return the first representable integer value greater than or equal to X. 
For positive values of X, this routine rounds away from zero. For negative 
values of X, this routine rounds toward zero.

但是 - 遗憾的是,它不是默认编译的 - 并且只有在使用 -DSQLITE_ENABLE_MATH_FUNCTIONS compile-time 选项编译合并时才有效。