SQL 为表中的每一行计算的 Postgres 数学表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1780242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Postgres math expression calculcated for each row in table
提问by nwb
Using PostgreSQL, supposing a table like the following:
使用 PostgreSQL,假设一个表如下:
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:
例如,将第 2 列除以第 3 列,输出将是:
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.
但是返回上限(即四舍五入)整数部分,我需要浮点值。
回答by Vinko Vrsalovic
Typical cast trick needed because col2 and col3 are integers (so result is by default an integer)
需要典型的转换技巧,因为 col2 和 col3 是整数(因此结果默认为整数)
select col1, col2/col3*1.0 from table
or
或者
select col1, col2/col3::float from table
or (SQL Standard way)
或(SQL 标准方式)
select col1, col2/cast(col3 as float) from table
回答by Dmitry
You can use arithmetic expressions in SELECT clause, like this:
您可以在 SELECT 子句中使用算术表达式,如下所示:
SELECT col1 / col2 AS new_name
FROM t
回答by Paul Tomblin
select col1, col2/col3 from table;
Should work. Aren't col2 and col3 numeric?
应该管用。col2 和 col3 不是数字吗?
回答by Szymon Lipiński
Try query like this:
试试这样的查询:
SELECT col1, col2 / col3::float FROM table_name;
回答by Ankit Vishwakarma
In PgSql the columns are typed. So if you want to operator on them; you need to cast the column.
在 PgSql 中,列是类型化的。因此,如果您想对它们进行操作;你需要投射列。
suppose you have a column 'minutes' and you wanna add '+5' in every values of column 'mintues'
假设您有一列“分钟”,并且您想在“分钟”列的每个值中添加“+5”
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+5 from my table
>> 语法错误
select *, minutes::int + 5 from mytable
>> give the output
select *, minutes::int + 5 from mytable
>> 给出输出