让我们首先创建一个表-
mysql> create table DemoTable1485 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentSubject varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Chris','MySQL'); mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB'); mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB'); mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Chris','Java');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1485;
这将产生以下输出-
+-----------+-------------+----------------+ | StudentId | StudentName | StudentSubject | +-----------+-------------+----------------+ | 1 | Chris | MySQL | | 2 | Robert | MongoDB | | 3 | Robert | MongoDB | | 4 | Chris | Java | +-----------+-------------+----------------+ 4 rows in set (0.00 sec)
这是根据条件对值进行计数的查询-
mysql> select StudentSubject, -> sum(case when StudentName = 'Chris' THEN 1 ELSE 0 END) Chris_Count, -> sum(case when StudentName = 'Robert' THEN 1 ELSE 0 END) Robert_Count -> from DemoTable1485 -> group by StudentSubject;
这将产生以下输出-
+----------------+-------------+--------------+ | StudentSubject | Chris_Count | Robert_Count | +----------------+-------------+--------------+ | MySQL | 1 | 0 | | MongoDB | 0 | 2 | | Java | 1 | 0 | +----------------+-------------+--------------+ 3 rows in set (0.00 sec)