Postgres数学表达式为表中的每一行计算

nwb*_*nwb 12 sql postgresql math

使用PostgreSQL,假设一个如下表:

 12184 |               4 |          83
 12183 |               3 |         171
 12176 |               6 |          95
Run Code Online (Sandbox Code Playgroud)

如何为表中的每一行计算数学表达式?

例如,要将第2列除以第3列,以便输出为:

 12184 |   0.04819277108
 12183 |   0.01754385965
 12176 |   0.06315789474
Run Code Online (Sandbox Code Playgroud)

我的直觉是尝试:

SELECT col1, col2 / col3 FROM table_name;
Run Code Online (Sandbox Code Playgroud)

但是返回上限(即向下舍入)整数部分,我需要浮点值.

Vin*_*vic 17

需要典型的强制转换技巧,因为col2和col3是整数(因此结果默认为整数)

select col1, col2/col3*1.0 from table
Run Code Online (Sandbox Code Playgroud)

要么

select col1, col2/col3::float from table
Run Code Online (Sandbox Code Playgroud)

或(SQL标准方式)

select col1, col2/cast(col3 as float) from table
Run Code Online (Sandbox Code Playgroud)