Postgres math expression calculcated for each row in table
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 p开发者_开发百科oint value.
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
select col1, col2/col3 from table;
Should work. Aren't col2 and col3 numeric?
Try query like this:
SELECT col1, col2 / col3::float FROM table_name;
In PgSql the columns are typed. So if you want to operator on them; you need to cast the column.
suppose you have a column 'minutes' and you wanna add '+5' in every values of column 'mintues'
Because you are adding and integer value the minutes column must be a integer only then the addition can be performed.
hence incorrect way:
select *, minutes+5 from my table
>> syntax error
select *, minutes::int + 5 from mytable
>> give the output
精彩评论