用于根据特定记录对值分组和求和的 MySQL 查询
使用 GROUP BY 对记录进行分组,而 SUM() 函数用于求和。我们先创建一个表 −
mysql> create table DemoTable ( Name varchar(40), Subject varchar(40), Marks int ); Query OK, 0 rows affected (2.89 sec)
使用 insert 命令向表中插入一些记录 −
mysql> insert into DemoTable values('Chris','MySQL',76); Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable values('Sam','MongoDB',86); Query OK, 1 row affected (0.39 sec) mysql> insert into DemoTable values('Mike','MySQL',98); Query OK, 1 row affected (0.46 sec) mysql> insert into DemoTable values('David','Java',93); Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable values('Bob','MySQL',57); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('John','MongoDB',77); Query OK, 1 row affected (0.17 sec)
使用 select 语句显示表中的所有记录 −
mysql> 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 对值进行分组和求和的查询 −
mysql> 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)
广告