关于在SQL中乘以列的问题

时间:2022-04-19 09:33:46

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

3 个解决方案

#1


12  

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

#2


1  

Yes you can perfectly do that.

是的,你可以做到这一点。

update

更新

To clarify: The query and output you mentioned in your question are correct.

澄清一下:您在问题中提到的查询和输出是正确的。

#3


0  

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;

#1


12  

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

#2


1  

Yes you can perfectly do that.

是的,你可以做到这一点。

update

更新

To clarify: The query and output you mentioned in your question are correct.

澄清一下:您在问题中提到的查询和输出是正确的。

#3


0  

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;