MySQL多个列有多个COUNT?
您可以将聚合函数SUM()
与一起使用IF()
。让我们首先创建一个表-
mysql> create table DemoTable(
FirstName varchar(100),
LastName varchar(100)
);
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Adam','Smith');mysql> insert into DemoTable values('John','Smith');
mysql> insert into DemoTable values('John','Doe');
mysql> insert into DemoTable values('Bob','Doe');
mysql> insert into DemoTable values('Sam','Smith');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-----------+----------+| FirstName | LastName |
+-----------+----------+
| Adam | Smith |
| John | Smith |
| John | Doe |
| Bob | Doe |
| Sam | Smith |
+-----------+----------+
5 rows in set (0.00 sec)
这是对MySQL具有多个列的COUNT个查询。
mysql> select sum(if(FirstName='John',1,0)) as John_Count,sum(if(LastName='Smith',1,0)) as Smith_Count from DemoTable;
这将产生以下输出-
+------------+-------------+| John_Count | Smith_Count |
+------------+-------------+
| 2 | 3 |
+------------+-------------+
1 row in set (0.00 sec)
以上是 MySQL多个列有多个COUNT? 的全部内容, 来源链接: utcz.com/z/316932.html