我遇到了一个我不知道如何解决的问题。这就是我的表格和我的表格#39;看起来像:
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| one | varchar(10) | YES | | NULL | |
| two | varchar(10) | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
mysql> SELECT * FROM myTable;
+----+-----------------+------------+
| id | one | two |
+----+-----------------+------------+
| 1 | cat | steve |
| 2 | cat | steve |
| 3 | cat | adam |
| 4 | dog | john |
| 5 | dog | adam |
| 6 | dog | alice |
| 7 | mouse | peter |
| 8 | mouse | peter |
| 9 | mouse | peter |
+----+-----------------+------------+
我之后的问题是查询“' one”中的每个唯一值。给了我两个'中唯一值的计数,即这给了我: 狗3(三个独特的名字) 猫2(两个独特的名字) 鼠标1(一个唯一的名称)
我一直在寻找,但不知道如何找到正确的答案,并且得到了:
SELECT one, two, COUNT(two) AS nr FROM myTable GROUP BY one, two ORDER BY one;
任何建议都非常感谢!提前谢谢。
答案 0 :(得分:4)
由于您需要统计不同的名称,因此需要使用distinct
关键字。
尝试此查询
select
one,
count(distinct two) as cnt
from
tbl
group by
one
| ONE | CNT |
---------------
| cat | 2 |
| dog | 3 |
| mouse | 1 |