MySQL 计算唯一值的数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16697215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:42:59  来源:igfitidea点击:

Count number of unique values

mysql

提问by thatidiotguy

If I have three columns:

如果我有三列:

orderNumber, name, email

and I would like to count how many unique emails are in the table how would I go about doing so?

我想计算表格中有多少独特的电子邮件我将如何进行?

A statement like:

像这样的声明:

SELECT count(email) FROM orders

gives me the total count.

给我总数。

I tried SELECT DISTINCT count(email) FROM orders

我试过 SELECT DISTINCT count(email) FROM orders

but that does not seem to be giving me the numbers I am expecting.

但这似乎并没有给我我期望的数字。

回答by Alpesh Gediya

use

SELECT count( DISTINCT(email) ) FROM orders

Distinct provide unique email ids and then simply count them.

Distinct 提供唯一的电子邮件 ID,然后简单地计算它们。

回答by BvuRVKyUVlViVIc7

SELECT  count(DISTINCT(email)) FROM orders

its different from your posting, since its filters out the duplicates before counting it

它与您的帖子不同,因为它在计算之前过滤掉了重复项

回答by Craig Jacobs

The accepted soultion doesn't work for me - it returns a "1" for each unique email address in the table.

接受的灵魂对我不起作用 - 它为表中的每个唯一电子邮件地址返回一个“1”。

This is what I had to do to get the info I needed:

这是我必须做的才能获得我需要的信息:

select email, count(email) AS total from sysAccessLog group by email order by total desc

Which returns a list of email addresses and the number of occurrences.

它返回电子邮件地址列表和出现次数。

回答by Piotr Musia?

For best performance you should use:

为了获得最佳性能,您应该使用:

SELECT 
sub.email, 
count(1) as 'count_unique' 
FROM 
(SELECT email FROM orders GROUP by email) sub