如何透過單個 MySQL 查詢計算不同獨立專案?


要計數專案,請使用 COUNT() 和 DISTINCT。此處,DISTINCT 用於返回不同值。現在,讓我們看一個示例並建立一個表 −

mysql> create table DemoTable
(
   CustomerId int,
   CustomerName varchar(20),
   ProductName varchar(40)
);
Query OK, 0 rows affected (1.02 sec)

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

mysql> insert into DemoTable values(101,'Chris','Product-1');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(102,'David','Product-2');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(101,'Chris','Product-1');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values(101,'Chris','Product-2');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(101,'Chris','Product-1');
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from DemoTable;

這將生成以下輸出 −

+------------+--------------+-------------+
| CustomerId | CustomerName | ProductName |
+------------+--------------+-------------+
|        101 | Chris        | Product-1   |
|        102 | David        | Product-2   |
|        101 | Chris        | Product-1   |
|        101 | Chris        | Product-2   |
|        101 | Chris        | Product-1   |
+------------+--------------+-------------+
5 rows in set (0.00 sec)

以下是用於在一個查詢中計數不同專案的查詢 −

mysql> select count(distinct ProductName) from DemoTable where CustomerId=101;

這將生成以下輸出 −

+-----------------------------+
| count(distinct ProductName) |
+-----------------------------+
|                           2 |
+-----------------------------+
1 row in set (0.00 sec)

更新時間:2019 年 10 月 7 日

110 次瀏覽

開闢你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.