在 SQLite 中找到数字的 ciel 和 floor 的最干净方法是什么?不幸的是,SQLite仅具有ROUND()
函数。
答案 0 :(得分:3)
天花板: 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()
函数检查了所有极端情况,包括负数。
答案 1 :(得分:2)
如果您手边的数字加上或减去0.5,则可以使用ROUND()
来达到CEIL
和FLOOR
的效果。我更喜欢这种方式,因为它更具可读性。
扩展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在下面的评论,我也没有想到这种极端情况。他的解决方案更加强大。