用于对具有重复相应 ID 的行求和的 MySQL 查询
总之,你可以使用聚合函数 SUM()。我们首先创建一个表 -
mysql> create table DemoTable850( Id int, Price int ); Query OK, 0 rows affected (0.54 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable850 values(1,90); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable850 values(2,100); Query OK, 1 row affected (0.55 sec) mysql> insert into DemoTable850 values(2,50); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable850 values(1,80); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable850 values(1,60); Query OK, 1 row affected (0.10 sec)
使用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable850;
这将产生以下输出 -
+------+-------+ | Id | Price | +------+-------+ | 1 | 90 | | 2 | 100 | | 2 | 50 | | 1 | 80 | | 1 | 60 | +------+-------+ 5 rows in set (0.00 sec)
以下是对具有重复值的行的和的查询 -
mysql> select Id,SUM(Price) from DemoTable850 where Id=1;
这将产生以下输出 -
+------+------------+ | Id | SUM(Price) | +------+------------+ | 1 | 230 | +------+------------+ 1 row in set (0.00 sec)
广告