CREATE TABLE SnowFall
(
date DATE,
snow INTEGER
);
INSERT INTO SnowFall VALUES('2023-02-01', 31);
INSERT INTO SnowFall VALUES('2023-02-02', 41);
INSERT INTO SnowFall VALUES('2023-02-03', 38);
INSERT INTO SnowFall VALUES('2023-02-04', 31);
INSERT INTO SnowFall VALUES('2023-02-05', 30);
INSERT INTO SnowFall VALUES('2023-02-06', 29);
INSERT INTO SnowFall VALUES('2023-02-07', 28);
INSERT INTO SnowFall VALUES('2023-02-08', 28);
INSERT INTO SnowFall VALUES('2023-02-09', 31);
INSERT INTO SnowFall VALUES('2023-02-10', 29);
INSERT INTO SnowFall VALUES('2023-02-11', 28);
INSERT INTO SnowFall VALUES('2023-02-12', 28);
INSERT INTO SnowFall VALUES('2023-02-13', 28);
INSERT INTO SnowFall VALUES('2023-02-14', 27);
INSERT INTO SnowFall VALUES('2023-02-15', 36);
INSERT INTO SnowFall VALUES('2023-02-16', 35);
INSERT INTO SnowFall VALUES('2023-02-17', 36);
INSERT INTO SnowFall VALUES('2023-02-18', 32);
INSERT INTO SnowFall VALUES('2023-02-19', 28);
INSERT INTO SnowFall VALUES('2023-02-20', 44);
INSERT INTO SnowFall VALUES('2023-02-21', 46);
INSERT INTO SnowFall VALUES('2023-02-22', 44);
INSERT INTO SnowFall VALUES('2023-02-23', 42);
INSERT INTO SnowFall VALUES('2023-02-24', 42);
INSERT INTO SnowFall VALUES('2023-02-25', 39);
INSERT INTO SnowFall VALUES('2023-02-26', 39);
INSERT INTO SnowFall VALUES('2023-02-27', 37);
INSERT INTO SnowFall VALUES('2023-02-28', 36);
解答
まずは最頻値から求めてみましょう。
SQLには最頻値を求める関数がないので、以下のようにクエリ文を組んで最頻値を取り出します。
SELECT
snow,
COUNT(*) AS cnt --①最深積雪量ごとの出現回数をカウント
FROM snowfall
GROUP BY snow
--すべての出現回数以上の出現回数、つまり最大の出現回数の行のみを表示
HAVING COUNT(*) >= ALL(SELECT COUNT(*) FROM snowfall
GROUP BY snow)
--- ①
WITH OrderSnow AS (
SELECT
date,
snow,
--- ROW_NUMBER()関数によって、最深積雪量の小さい順に1から数字を割り当てる
ROW_NUMBER() OVER(order by snow) as order_id,
--- ct列に日数(=28)を入れる
(SELECT COUNT(*) FROM SnowFall) AS ct
FROM SnowFall
)
SELECT
--- ③
AVG(snow) AS median
FROM OrderSnow
--- ②
WHERE order_id BETWEEN ct/2 AND ct/2 + 1
コメント