在单个查询中统计 MySQL 中的两个不同的列?
你可以使用 CASE 语句在单个查询中统计两个不同的列。为了理解这个概念,我们首先创建一个表。创建表的查询如下。
mysql> create table CountDifferentDemo - > ( - > ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > ProductName varchar(20), - > ProductColor varchar(20), - > ProductDescription varchar(20) - > ); Query OK, 0 rows affected (1.06 sec)
使用 insert 命令在表中插入一些记录。
查询如下
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-1','Red','Used');
Query OK, 1 row affected (0.46 sec)
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-1','Blue','Used');
Query OK, 1 row affected (0.17 sec)
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-2','Green','New');
Query OK, 1 row affected (0.12 sec)
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-2','Blue','New');
Query OK, 1 row affected (0.14 sec)
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-3','Green','New');
Query OK, 1 row affected (0.21 sec)
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-4','Blue','Used');
Query OK, 1 row affected (0.20 sec)使用 select 语句显示表中的所有记录。
查询如下
mysql> select *from CountDifferentDemo;
输出如下
+-----------+-------------+--------------+--------------------+ | ProductId | ProductName | ProductColor | ProductDescription | +-----------+-------------+--------------+--------------------+ | 1 | Product-1 | Red | Used | | 2 | Product-1 | Blue | Used | | 3 | Product-2 | Green | New | | 4 | Product-2 | Blue | New | | 5 | Product-3 | Green | New | | 6 | Product-4 | Blue | Used | +-----------+-------------+--------------+--------------------+ 6 rows in set (0.01 sec)
以下是对单个查询中的两个不同列进行统计的查询,即我们正在计算特定颜色“红色”和描述“新”的出现。
mysql> select ProductName, - > SUM(CASE WHEN ProductColor = 'Red' THEN 1 ELSE 0 END) AS Color, - > SUM(CASE WHEN ProductDescription = 'New' THEN 1 ELSE 0 END) AS Desciption - > from CountDifferentDemo - > group by ProductName;
输出如下
+-------------+-------+------------+ | ProductName | Color | Desciption | +-------------+-------+------------+ | Product-1 | 1 | 0 | | Product-2 | 0 | 2 | | Product-3 | 0 | 1 | | Product-4 | 0 | 0 | +-------------+-------+------------+ 4 rows in set (0.12 sec)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP