根据 MySQL 中的条件对一列进行求和
我们首先创建一个表 −
mysql> create table DemoTable ( CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY, ProductAmount int, CustomerCountryName varchar(10) ); Query OK, 0 rows affected (0.86 sec)
在表中使用插入命令插入一些记录 −
mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(190,'US'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(200,'UK'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(1500,'AUS'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(2010,'US'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(7890,'UK'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(500,'US'); Query OK, 1 row affected (0.21 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+------------+---------------+---------------------+ | CustomerId | ProductAmount | CustomerCountryName | +------------+---------------+---------------------+ | 1 | 190 | US | | 2 | 200 | UK | | 3 | 1500 | AUS | | 4 | 2010 | US | | 5 | 7890 | UK | | 6 | 500 | US | +------------+---------------+---------------------+ 6 rows in set (0.00 sec)
以下是根据条件求和一列的查询。在此,您希望对国家/地区为“美国”的客户进行求和 −
mysql> select SUM(ProductAmount) AS Total_Amount from DemoTable where CustomerCountryName='US';
这将产生以下输出 −
+--------------+ | Total_Amount | +--------------+ | 2700 | +--------------+ 1 row in set (0.00 sec)
广告