我有一个带有2个INT字段的sqlite3表。 (通过和失败)
我想计算%Passed,所以使用以下SQL
SELECT id,
passed,
failed,
passed / (passed + failed )* 100 AS 'passedPC'
FROM myData
如果Passed为23且Failed为3,则返回0,这是意外的。
为什么会这样?
答案 0 :(得分:3)
这是因为你正在进行整数除法和23/26=0
。你需要强制它做浮点除法。最简单的方法是将一个值乘以1.0
,如下所示:
SELECT id, passed, failed, ((passed * 1.0) / (passed + failed )) * 100 AS 'passedPC'
FROM myData
或者,您可以使用cast operator将列强制为real
数据类型:
SELECT id, passed, failed, cast(passed as real) / (passed + failed ) * 100 AS 'passedPC'
FROM myData;
Sample SQL Fiddle显示差异。
答案 1 :(得分:0)
整数除法会截断结果。
您可以在除法之前相乘和/或转换为其他数据类型:
SELECT id, passed, failed,
100 * passed / (passed + failed ) AS 'passedPC'
FROM myData
SELECT id, passed, failed,
100.00 * passed / (passed + failed ) AS 'passedPC'
FROM myData