MySQL查询基于特定记录对值进行分组和求和
使用GROUPBY对记录进行分组,而SUM()函数用于添加。让我们首先创建一个表-
create table DemoTable ( Name varchar(40), Subject varchar(40), Marks int );
使用插入命令在表中插入一些记录-
insert into DemoTable values('Chris','MySQL',76); insert into DemoTable values('Sam','MongoDB',86); insert into DemoTable values('Mike','MySQL',98); insert into DemoTable values('David','Java',93); insert into DemoTable values('Bob','MySQL',57); insert into DemoTable values('John','MongoDB',77);
使用select语句显示表中的所有记录-
select *from DemoTable;
这将产生以下输出-
+-------+---------+-------+ | Name | Subject | Marks | +-------+---------+-------+ | Chris | MySQL | 76 | | Sam | MongoDB | 86 | | Mike | MySQL | 98 | | David | Java | 93 | | Bob | MySQL | 57 | | John | MongoDB | 77 | +-------+---------+-------+ 6 rows in set (0.00 sec)
以下是根据SUBJECT对值进行分组和求和的查询-
select Subject,SUM(Marks) from DemoTable group by Subject;
这将产生以下输出-
+---------+------------+ | Subject | SUM(Marks) | +---------+------------+ | MySQL | 231 | | MongoDB | 163 | | Java | 93 | +---------+------------+ 3 rows in set (0.00 sec)