如何通过单个 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)
广告