Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculation field using division in SQLite3

Tags:

sql

sqlite

I have a sqlite3 table with 2 fields of INT. (Passed and Failed)

I want to calculate % Passed so am using the following SQL

SELECT id,
       passed,
       failed,
       passed / (passed + failed )* 100 AS 'passedPC'
  FROM myData

if Passed is 23 and Failed is 3 I am getting 0 returned which is unexpected.

Why is this?

like image 791
Matt A Avatar asked Jul 17 '26 21:07

Matt A


1 Answers

It's because you are doing integer division and 23/26=0. You need to force it to do floating point division instead. The easiest way is to multiply one value with 1.0 like this:

SELECT id, passed, failed, ((passed * 1.0) / (passed + failed )) * 100 AS 'passedPC' 
FROM myData

Alternatively you could use the cast operator to force a a column to the real data type:

SELECT id, passed, failed, cast(passed as real) / (passed + failed ) * 100 AS 'passedPC' 
FROM myData;

Sample SQL Fiddle showing the difference.

like image 200
jpw Avatar answered Jul 20 '26 10:07

jpw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!