在單個查詢中統計 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)

更新於: 30-7-2019

5K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告