在結果集中顯示每個值總計的 MySQL 查詢,對列中的 3 個不同值求和?


為此,可以使用 CASE 語句。讓我們首先建立一個表 -

mysql> create table DemoTable
(
   ProductName varchar(100),
   ProductRating ENUM('1','2','3')
);
Query OK, 0 rows affected (0.50 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable values('Product-1',3);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Product-2',1);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Product-3',2);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Product-1',2);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Product-3',3);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Product-2',2);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Product-3',3);
Query OK, 1 row affected (0.10 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable;

這將產生以下輸出 -

+-------------+---------------+
| ProductName | ProductRating |
+-------------+---------------+
| Product-1   | 3             |
| Product-2   | 1             |
| Product-3   | 2             |
| Product-1   | 2             |
| Product-3   | 3             |
| Product-2   | 2             |
| Product-3   | 3             |
+-------------+---------------+
7 rows in set (0.00 sec)

以下是如何在列中對 3 個不同的值求和,在結果集中顯示每個值的總計。我們根據產品評級進行加法 -

mysql> select ProductName,
   sum( case when ProductRating=3 then 1 else 0 end ) as Product_3_Rating,
   sum( case when ProductRating=2 then 1 else 0 end ) as Product_2_Rating,
   sum( case when ProductRating=1 then 1 else 0 end ) as Product_1_Rating
   from DemoTable
   group by ProductName;

這將產生以下輸出 -

+-------------+------------------+------------------+------------------+
| ProductName | Product_3_Rating | Product_2_Rating | Product_1_Rating |
+-------------+------------------+------------------+------------------+
| Product-1   |                1 |                1 |                0 |
| Product-2   |                0 |                1 |                1 |
| Product-3   |                2 |                1 |                0 |
+-------------+------------------+------------------+------------------+
3 rows in set (0.00 sec)

更新於: 2019 年 10 月 1 日

159 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.