0
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 1 year has passed since last update.

SQLで中央値をとる

Last updated at Posted at 2023-05-20

alphavantage APIとか使って、以下のような株アプリを作ってる

SQL Chat 活用

SQL Chat・ChatGPT を活用し、Median(中央値)を求める方法を説明します。

テスト用テーブルの作成

SQL Chat を使い、テーブルを作るSQL文を生成してもらいました。
(ChatGPTに聞いているのと同じ)

キャプチャ.PNG

CREATE TABLE salary_info 
( id INT NOT NULL AUTO_INCREMENT,
 employee_id INT NOT NULL, 
salary INT NOT NULL, 
bonus INT NOT NULL, 
allowance INT NOT NULL, 
tax INT NOT NULL, 
total_salary INT NOT NULL, 
payment_date DATE NOT NULL, PRIMARY KEY (id) );

データの登録

insert文も SQL Chatにお願いしてみた。正解にいたるまで、いろいろエラーになる回答を出してきましたね。

キャプチャ-1.png

DELIMITER //

CREATE PROCEDURE insert_salary_info()
BEGIN
  DECLARE i INT DEFAULT 1;
  WHILE i <= 100000 DO
    INSERT INTO salary_info (employee_id, salary, bonus, allowance, tax, total_salary, payment_date)
    VALUES (
      FLOOR(RAND() * 1000) + 1,
      FLOOR(RAND() * 500000) + 100000,
      FLOOR(RAND() * 100000),
      FLOOR(RAND() * 50000),
      FLOOR(RAND() * 100000),
      (salary + bonus + allowance) - tax,
      DATE_ADD('2021-01-01', INTERVAL FLOOR(RAND() * 365) DAY)
    );
    SET i = i + 1;
  END WHILE;
END //

DELIMITER ;
CALL insert_salary_info();

本当のMedian 関数の使い方

中央値はMedian関数を使います。
distinctしないと行数文出力されるから、注意しましょう。
over()に何も指定しないと全行に対する中央値となります。

MariaDB [sqlchat]>  select distinct median(salary) over() from salary_info;
+-----------------------+
| median(salary) over() |
+-----------------------+
|     349909.0000000000 |
+-----------------------+
1 row in set (0.105 sec)

SQL Chatが回答したMedian関数

SQL Chatは、Median関数ではなく、ずいぶん複雑なSQLを出してきました。このあたり、まだまだですね。

キャプチャ-2.png

しかも間違い

キャプチャ-3.png

0
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
0
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?