Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-casting issue

Tags:

sqlite

In the following query, the answer of 1/2 is always zero while it should be 0.5. Can you please tell me how to convert the two int columns into float/double?

SELECT 1/2, total, sb_ondate, likes
  FROM (
      SELECT sb_ondate, COUNT(*) AS total,
             STRFTIME("%w",sb_ondate) AS weekDay,
             COUNT(CASE WHEN sb_reaction = 'like' THEN sb_id END) AS likes
        FROM diet
    GROUP BY weekDay) AS f;

Thanks.

like image 910
Volatil3 Avatar asked May 22 '11 01:05

Volatil3


People also ask

What is type casting error?

The compiler is (trying to) tell you you can't typecast a string to an int . The thing you are doing wrong is trying to typecast a string to an int .

Is type casting bad?

Being typecast can be lucrative if an actor enjoys the roles they're playing, but it can also feel stifling because it's difficult for the actor to grow and try new things. It's very common for new actors to worry about being typecast because they don't want to be locked into only playing a particular character type.

What is an example of type casting?

In type casting, the compiler automatically changes one data type to another one depending on what we want the program to do. For instance, in case we assign a float variable (floating point) with an integer (int) value, the compiler will ultimately convert this int value into the float value.

What is type casting explain?

Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double.


2 Answers

Cast one of the two divisors as a real:

SELECT 1 / CAST(2 AS REAL),...

Sample interactive Python session:

>>> import sqlite3
>>> c = sqlite3.connect(':memory:')
>>> c.execute("create table t (a int,b int);")
<sqlite3.Cursor object at 0x7f9b0e9539d0>
>>> c.execute("insert into t values (1,2)")
<sqlite3.Cursor object at 0x7f9b0e953ad8>
>>> conn.execute("select a / cast(b as real) from t").fetchone()
(0.5,)
like image 182
mechanical_meat Avatar answered Oct 18 '22 03:10

mechanical_meat


Add .0 to one of the constants:

sqlite> select 1/2;
1/2
----------
0
sqlite> select 1.0/2;
1.0/2
----------
0.5
like image 34
Samuel Neff Avatar answered Oct 18 '22 03:10

Samuel Neff