在单个MySQL查询中计算不同的不同项目?
要计数项目,请使用COUNT()和DISTINCT。在这里,DISTINCT用于返回不同的值。现在让我们看一个示例并创建一个表-
create table DemoTable ( CustomerId int, CustomerName varchar(20), ProductName varchar(40) );
使用插入命令在表中插入一些记录-
insert into DemoTable values(101,'Chris','Product-1'); insert into DemoTable values(102,'David','Product-2'); insert into DemoTable values(101,'Chris','Product-1'); insert into DemoTable values(101,'Chris','Product-2'); insert into DemoTable values(101,'Chris','Product-1');
使用select语句显示表中的所有记录-
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)
以下是在单个查询中计算不同项目的查询-
select count(distinct ProductName) from DemoTable where CustomerId=101;
这将产生以下输出-
+-----------------------------+ | count(distinct ProductName) | +-----------------------------+ | 2 | +-----------------------------+ 1 row in set (0.00 sec)
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便