要从多个列计算值,请使用GROUP BY。以下是语法-
select yourColumnName1,sum(yourColumnName2*yourColumnName3) AS anyAliasName from yourTableName group by yourColumnName1;
让我们首先创建一个表-
mysql> create table calculateValueDemo -> ( -> Id int, -> ProductPrice int, -> ProductWeight int -> );
以下是使用insert命令在表中插入记录的查询-
mysql> insert into calculateValueDemo values(100,35,5); mysql> insert into calculateValueDemo values(101,50,3); mysql> insert into calculateValueDemo values(100,100,4); mysql> insert into calculateValueDemo values(101,500,2);
以下是使用select语句显示表中所有记录的查询-
mysql> select * from calculateValueDemo;
这将产生以下输出-
+------+--------------+---------------+ | Id | ProductPrice | ProductWeight | +------+--------------+---------------+ | 100 | 35 | 5 | | 101 | 50 | 3 | | 100 | 100 | 4 | | 101 | 500 | 2 | +------+--------------+---------------+ 4 rows in set (0.00 sec)
这是从多个列中计算值的查询-
mysql> select Id,sum(ProductPrice*ProductWeight) AS Total from calculateValueDemo group by Id;
这将产生以下输出-
+------+-------+ | Id | Total | +------+-------+ | 100 | 575 | | 101 | 1150 | +------+-------+ 2 rows in set (0.00 sec)