Help us understand the problem. What is going on with this article?

SQL | COUNT(DISTINCT column_name) は「同じ値の種類数」をカウントする

More than 1 year has passed since last update.

初歩。

テーブル例

こんなテーブルがある場合。

mysql> SELECT * FROM scores ORDER BY name;
+-------+--------+-------+
| name  | sex    | score |
+-------+--------+-------+
| Alice | female |    60 |
| Bob   | male   |    70 |
| Carol | female |    70 |
| David | male   |    80 |
| Eric  | male   |    80 |
+-------+--------+-------+

sex には male / famale の二種類がある。

mysql> SELECT COUNT(DISTINCT(sex)) AS sex_kind FROM scores;

+----------+
| sex_kind |
+----------+
|        2 |
+----------+

score には 60点 / 70点 / 80点の三種類がある。

mysql> SELECT COUNT(DISTINCT(score)) AS score_kind FROM scores;

+------------+
| score_kind |
+------------+
|          3 |
+------------+

環境

  • mysql Ver 14.14 Distrib 5.5.56, for osx10.12 (x86_64) using EditLine wrapper

参考

YumaInaura
Ruby on Rails 業務経験 約5年 / Perl PHP Python Golang Linux Apache MySQL BigQuery Jenkins ansible AWS など / いなうらゆうま / YumaInaura / 稲浦悠馬
http://twitter.com/yumainaura
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away