Question

I don't dabble in SQL queries much and rely on google when I need something more than the basics, and have come up with a problem.

I am trying to calculate a value and it returns a result rounded down to the nearest integer.

To test this out, I wrote the following query:

select ELAPTIME AS "ELAPSEC", ELAPTIME/60 AS "ELAPMIN" from CMR_RUNINF

The result is:

+-----------+-----------+
|ELAPSEC    |ELAPMIN    |
+-----------+-----------+
|258        |4          |
+-----------+-----------+
|0          |0          |
+-----------+-----------+
|2128       |35         |
+-----------+-----------+
|59         |0          |
+-----------+-----------+

I'm trying to do a bit more than this, but I've simplified it to make it easier to explain the problem. How do I ensure that this calculation returns the decimal point?

Was it helpful?

Solution 2

Your SQL product performs integral division because both operands are integers. ELAPTIME's integer type is determined be the table structure and 60 is automatically assumed to be integer because it has no decimal point.

There are two methods of resolving the issue:

  1. Convert either operand to a non-integer numeric type explicitly:

    CAST(ELAPTIME AS float) / 60
    
  2. Write 60.0 instead of 60 so that the parser can see you are not dividing an integer by an integer:

    ELAPTIME / 60.0
    

OTHER TIPS

postgres=# SELECT 258/60::float;
 ?column? 
----------
      4.3
(1 row)

Simply try this

SELECT ELAPTIME AS "ELAPSEC", ELAPTIME/60 :: Float AS "ELAPMIN" 
FROM CMR_RUNINF

Or:

SELECT ELAPTIME AS "ELAPSEC", ELAPTIME/60 :: Real AS "ELAPMIN" 
FROM CMR_RUNINF

Fiddle Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top