我可以为 SQL 中的特定列设置公式吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2415398/
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
Can I set a formula for a particular column in SQL?
提问by Jagira
I want to implement something like Col3 = Col2 + Col1 in SQL.
我想在 SQL 中实现类似 Col3 = Col2 + Col1 的东西。
This is somewhat similar to Excel, where every value in column 3 is sum of corresponding values from column 2 and column 1.
这有点类似于 Excel,其中第 3 列中的每个值都是第 2 列和第 1 列中相应值的总和。
采纳答案by codaddict
Yes, you can do it in SQL using the UPDATE command:
是的,您可以使用 UPDATE 命令在 SQL 中执行此操作:
UPDATE TABLE table_name
SET col3=col1+col2
WHERE <SOME CONDITION>
This assumes that you already have a table with populated col1 and col2 and you want to populate col3.
这假设您已经有一个包含 col1 和 col2 的表,并且您想要填充 col3。
回答by Adriaan Stander
Have a look at Computed Columns
看看计算列
A computed column is computed from an expression that can use other columns in the same table. The expression can be a noncomputed column name, constant, function, and any combination of these connected by one or more operators.
计算列是根据可以使用同一表中其他列的表达式计算得出的。表达式可以是一个非计算列名、常量、函数,以及由一个或多个运算符连接的这些的任意组合。
Also from CREATE TABLEpoint J
同样来自CREATE TABLE点 J
Something like
就像是
CREATE TABLE dbo.mytable
( low int, high int, myavg AS (low + high)/2 ) ;
回答by Timothy
Yes. Provided it is not aggregating data across rows.
是的。前提是它不跨行聚合数据。
assume that col1
and col2
are integers.
假设col1
和col2
是整数。
SELECT col1, col2, (col1 + col2) as col3 FROM mytable