1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SQLパズル 29 最頻値を求める 解法メモその3

Last updated at Posted at 2024-11-15

概要

p126 29 最頻値を求める 解法メモその3

Having句とALL述語を組み合わせて最頻値を求めています。

要件

支払い伝票に対して、金額の最頻値を求めたい。
※最頻値とは、母集団の中で最も多かった値

image.png

SQL

DDL

drop table if EXISTS Payroll;
create table Payroll(
    check_nbr Integer NOT NULL Primary Key,
    check_amt DECIMAL(8,2) NOT NULL
);

INSERT INTO Payroll VALUES(1, 100);
INSERT INTO Payroll VALUES(2, 100);
INSERT INTO Payroll VALUES(3, 200);
INSERT INTO Payroll VALUES(4, 150);
INSERT INTO Payroll VALUES(5, 300);
INSERT INTO Payroll VALUES(6, 150);
INSERT INTO Payroll VALUES(7, 300);
INSERT INTO Payroll VALUES(8, 300);
INSERT INTO Payroll VALUES(9, 100);

答えのSQL

ALL述語を使っています。
Having COUNT() >= ALL ()なので、COUNT()が最大値の時以外 偽です。
今回の場合だと
check_amtが
300,100 →最大値の3なので 3 > ALL(3,2,1)を満たすので真
150,200 → 1 or 2なので  1 or 2 >ALL(3,2,1)を満たさないので偽

SELECT check_amt,COUNT(*) AS check_cnt
FROM Payroll
GROUP BY check_amt
HAVING COUNT(*) >= ALL (SELECT COUNT(*) AS check_cnt
                        FROM Payroll
                        GROUP BY check_amt)
                        ;

image.png

参考

SQLパズル p126 29 最頻値を求める その3

SQLパズル サポートページ
https://mickindex.sakura.ne.jp/database/db_support_sqlpuzzle.html#LocalLink-p29

達人に学ぶSQL徹底指南書第2版 p111 最頻値を求める ALL述語の利用

github
https://github.com/RYA234/SQL_Puzzle_Learning/commit/e9f30131f0bff66e2151704836ca7a74a8033894

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?