获取 MySQL 中带有条件的列求和
我们先创建一个表 -
mysql> create table DemoTable1489 -> ( -> ProductId int, -> ProductPrice int -> ); Query OK, 0 rows affected (0.49 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable1489 values(100,900); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1489 values(115,1000); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1489 values(119,2100); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1489 values(125,2100); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1489 values(128,2900); Query OK, 1 row affected (0.25 sec)
使用 select 语句在表中显示所有记录 -
mysql> select * from DemoTable1489;
这将生成以下输出 -
+-----------+--------------+ | ProductId | ProductPrice | +-----------+--------------+ | 100 | 900 | | 115 | 1000 | | 119 | 2100 | | 125 | 2100 | | 128 | 2900 | +-----------+--------------+ 5 rows in set (0.00 sec)
以下是对带有条件的列求和的查询 -
mysql> select ProductId div 10,sum(ProductPrice) from DemoTable1489 -> group by ProductId div 10;
这将生成以下输出 -
+------------------+-------------------+ | ProductId div 10 | sum(ProductPrice) | +------------------+-------------------+ | 10 | 900 | | 11 | 3100 | | 12 | 5000 | +------------------+-------------------+ 3 rows in set (0.00 sec)
广告