根据条件对值进行计数,并将结果显示在具有不同列的 MySQL 中吗?
我们首先创建一个表 -
mysql> create table DemoTable1485 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentSubject varchar(20) -> ); Query OK, 0 rows affected (0.72 sec)
使用 insert 命令在表中插入某些记录 -
mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Chris','MySQL'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Chris','Java'); Query OK, 1 row affected (0.12 sec)
使用 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)
广告