1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

HAVING句にサブクエリを使うことで最頻値を求める方法

Last updated at Posted at 2021-12-13

はじめに

HAVING句を使って、サブクエリを使うことで最頻値を求める方法を紹介します。

実行結果はこちらで確認できます。

テーブル

例題として、以下のような、大学の卒業生の初任給が情報(graduatesテーブル)があるとします。

id name income
1 sampson 400000
2 mike 30000
3 white 20000
4 arnold 20000
5 smith 20000
6 rolens 15000
7 hadson 15000
8 kent 10000
9 becker 10000
10 scot 10000

データは下記を参考にしています。

Schema (MySQL v8.0)

 CREATE TABLE graduates (
        id INT NOT NULL PRIMARY KEY auto_increment,
        name TEXT NOT NULL,
        income INT NOT NULL
    );

    INSERT INTO graduates VALUES
        ( 1, 'sampson', 400000),
        ( 2, 'mike',       30000),
        ( 3, 'white',      20000),
        ( 4, 'arnold',     20000),
        ( 5, 'smith',      20000),
        ( 6, 'rolens',     15000),
        ( 7, 'hadson',   15000),
        ( 8, 'kent',      10000),
        ( 9, 'becker',   10000),
        (10, 'scot',     10000);

データを眺めると、20000が3回、15000が3回とこの2つが最頻値です。

このデータの最頻値を求めるクエリはどう書きますか?

Query

SELECT income, COUNT(*) AS cnt
FROM graduates
GROUP BY income
HAVING COUNT(*) >= ALL ( SELECT COUNT(*) AS cnt FROM graduates GROUP BY income )

グループ化されたものを、HAVINGでカウントしています。

これだけだと、

SELECT income, COUNT(*) AS cnt
FROM graduates
GROUP BY income
HAVING COUNT(*)
income cnt
400000 1
30000 1
20000 3
15000 2
10000 3

こんなデータになりますよね?

それをALL句でtrueになるものだけ呼び出されて、以下のような結果になってます。

Results

income cnt
20000 3
10000 3

参照

111 - 113p

アウトプット100本ノック実施中

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?