在 MySQL 中,如何在单个查询中计算两个不同的列?

mysqlmysqli database

您可以使用 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)

相关文章