Using PostgreSQL, supposing a table like the following:
12184 | 4 | 83
12183 | 3 | 171
12176 | 6 | 95
How can I compute a math expression for each row in the table?
For example, to divide column 2 by column 3, such that the output would be:
12184 | 0.04819277108
12183 | 0.01754385965
12176 | 0.06315789474
My instinct was to try:
SELECT col1, col2 / col3 FROM table_name;
But that return the ceiling (ie. rounded-down) integer part, I need the floating point value.
So, the short answer is that you can't, and that is by design. The notable exception to this is Microsoft Access, where you can indeed use calculations in subsequent columns and WHERE clauses.
In PostgreSQL, the / operator stands for division. If the columns have integer types, PostgreSQL will use integer division. Integer division is division in which the fractional part (remainder) is discarded. For example, in integer division, the result of 5/2 is 2.
Type Casts. A type cast specifies a conversion from one data type to another. PostgreSQL accepts two equivalent syntaxes for type casts: CAST ( expression AS type ) expression :: type. The CAST syntax conforms to SQL; the syntax with :: is historical PostgreSQL usage.
Summary. Use the SUM() function to calculate the sum of values. Use the DISTINCT option to calculate the sum of distinct values. Use the SUM() function with the GROUP BY clause to calculate the sum for each group.
Typical cast trick needed because col2 and col3 are integers (so result is by default an integer)
select col1, col2/col3*1.0 from table
or
select col1, col2/col3::float from table
or (SQL Standard way)
select col1, col2/cast(col3 as float) from table
You can use arithmetic expressions in SELECT clause, like this:
SELECT col1 / col2 AS new_name
FROM t
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With