SQL 关于SQL中列相乘的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5466901/
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
Question about multiplying columns in SQL
提问by Steffan Harris
I was wondering if it was possible to multiply two columns and if so how would this take place
我想知道是否可以将两列相乘,如果可以,这将如何发生
Suppose I have a table
假设我有一张桌子
a b
1 4
2 5
3 6
Could I do something like
我可以做类似的事情吗
SELECT a *b from table
Would this multiply the contents row by row then store it in a new column
这是否将内容逐行相乘,然后将其存储在新列中
Are these result right
这些结果是否正确
4
10
18
回答by NotMe
That query would multiply the values, but it wouldn't "store it in a new column" To store it you would have to issue an update statement.
该查询会将值相乘,但不会“将其存储在新列中”要存储它,您必须发出更新语句。
Assuming you add a new column ("c") to your table you could do:
假设您向表中添加了一个新列(“c”),您可以执行以下操作:
update table
set c = a * b
If all you need is the new column in a result set, without modifying the underlying table you could:
如果您只需要结果集中的新列,而无需修改基础表,您可以:
select a, b, (a*b) as c from table
回答by Alp
Yes you can perfectly do that.
是的,你可以完美地做到这一点。
update
更新
To clarify: The query and output you mentioned in your question are correct.
澄清:您在问题中提到的查询和输出是正确的。
回答by onedaywhen
Rather than storing a calculated column in a base table, consider a viewed table:
考虑一个查看表,而不是在基表中存储计算列:
CREATE VIEW MyView
AS
SELECT a, b,
a * b AS my_calc
FROM MyTable;