让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Subject varchar(20), Price int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Subject,Price) values('MySQL',456); mysql> insert into DemoTable(Subject,Price) values('MySQL',456); mysql> insert into DemoTable(Subject,Price) values('MongoDB',56); mysql> insert into DemoTable(Subject,Price) values('MongoDB',60); mysql> insert into DemoTable(Subject,Price) values('Java',100); mysql> insert into DemoTable(Subject,Price) values('Java',130);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
输出结果
+----+---------+-------+ | Id | Subject | Price | +----+---------+-------+ | 1 | MySQL | 456 | | 2 | MySQL | 456 | | 3 | MongoDB | 56 | | 4 | MongoDB | 60 | | 5 | Java | 100 | | 6 | Java | 130 | +----+---------+-------+ 6 rows in set (0.00 sec)
这是在MySQL中使用GROUB BY获取行的查询-
mysql> select sum(Price) AS Total, Subject from DemoTable group by Subject;
输出结果
+-------+---------+ | Total | Subject | +-------+---------+ | 912 | MySQL | | 116 | MongoDB | | 230 | Java | +-------+---------+ 3 rows in set (0.04 sec)