不使用MySQL COUNT()执行多次计数?
要进行计数,可以将SUM()与CASE语句一起使用来确定条件。让我们首先创建一个表-
create table DemoTable1485 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentSubject varchar(20) -> );
使用插入命令在表中插入一些记录-
insert into DemoTable1485(StudentName,StudentSubject) values('Chris','MySQL'); insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB'); insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB'); insert into DemoTable1485(StudentName,StudentSubject) values('Chris','Java');
使用select语句显示表中的所有记录-
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)
这是不使用COUNT()方法即可执行多次计数的查询-
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)