获取MySQL中条件的列总和
让我们首先创建一个表-
mysql> create table DemoTable1489 -> ( -> ProductId int, -> ProductPrice int -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1489 values(100,900); mysql> insert into DemoTable1489 values(115,1000); mysql> insert into DemoTable1489 values(119,2100); mysql> insert into DemoTable1489 values(125,2100); mysql> insert into DemoTable1489 values(128,2900);
使用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)