为了理解这一点,让我们创建一个包含ID,客户名称,项目,价格等字段的表。我们将首先将商品乘以价格。之后,将添加具有相似记录(即相同客户名称)的行。
让我们首先创建一个表:
mysql> create table DemoTable ( CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY, CustomerName varchar(100), CustomerItems int, CustomerPrice int );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable(CustomerName,CustomerItems,CustomerPrice)values('Larry',3,450); mysql> insert into DemoTable(CustomerName,CustomerItems,CustomerPrice)values('Mike',2,550); mysql> insert into DemoTable(CustomerName,CustomerItems,CustomerPrice)values('Larry',4,1000); mysql> insert into DemoTable(CustomerName,CustomerItems,CustomerPrice)values('Larry',1,100); mysql> insert into DemoTable(CustomerName,CustomerItems,CustomerPrice)values('Mike',5,200);
以下是使用select命令显示表中记录的查询:
mysql> select *from DemoTable;
这将产生以下输出
+------------+--------------+---------------+---------------+ | CustomerId | CustomerName | CustomerItems | CustomerPrice | +------------+--------------+---------------+---------------+ | 1 | Larry | 3 | 450 | | 2 | Mike | 2 | 550 | | 3 | Larry | 4 | 1000 | | 4 | Larry | 1 | 100 | | 5 | Mike | 5 | 200 | +------------+--------------+---------------+---------------+ 5 rows in set (0.00 sec)
这是将列(项目*价格)相乘,然后对记录相似的行求和的查询:
mysql> SELECT CustomerName, SUM( CustomerItems* CustomerPrice) AS TOTAL_PRICE FROM DemoTable GROUP BY CustomerName;
这将产生以下输出
+--------------+-------------+ | CustomerName | TOTAL_PRICE | +--------------+-------------+ | Larry | 5450 | | Mike | 2100 | +--------------+-------------+ 2 rows in set (0.05 sec)