计算不同的值 [英] Count distinct values
问题描述
我有一个数据集,询问客户例如他们有多少只宠物.有一种方法可以查询一个不同的值(1、2、3等)吗? 谢谢!
I have a data set asking a customer how many pets they have for example. Is there a way with one query I can count the distinct values (1,2,3, etc)? Thanks!
+----------+------+
| Customer | Pets |
+----------+------+
| 20 | 2 |
| 21 | 3 |
| 22 | 3 |
| 23 | 2 |
| 24 | 4 |
+----------+------+
我想要的是一个清单,上面写着:
What I want is a list saying:
- 2养了2只宠物
- 2养了3只宠物
- 1只养了4只宠物
推荐答案
您可以进行以下不同的计数:
You can do a distinct count as follows:
SELECT COUNT(DISTINCT column_name) FROM table_name;
在您对问题进行澄清和更新之后,我现在看到的是与我们最初想到的问题完全不同的问题. "DISTINCT"在SQL中具有特殊含义.如果我理解正确,那么您需要这样的东西:
Following your clarification and update to the question, I see now that it's quite a different question than we'd originally thought. "DISTINCT" has special meaning in SQL. If I understand correctly, you want something like this:
- 2位顾客养了1只宠物
- 3位顾客养了2只宠物
- 1位顾客养了3只宠物
现在您可能要使用子查询:
Now you're probably going to want to use a subquery:
select COUNT(*) column_name FROM (SELECT DISTINCT column_name);
让我知道这是否与您想要的不一样.
Let me know if this isn't quite what you're looking for.
这篇关于计算不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!