9
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.

MySQLで最小値/最大値を取得する

Last updated at Posted at 2020-11-06

やりたいこと

最小値かつ最小値のグループの中の最大値を取得したい

条件

開始日が1番古い値の処理日時を取得する
※開始日が被っていた場合(時間は見ない)には処理日時が一番新しいものを取得

ここでは開始日が『 9/16 16:45 』で処理日時が『 9/20 13:23 』の2行目の値を取得します。

テーブル名:item

開始日(start_time) 処理日時(process_time)
9/16 15:34 9/17 10:43
9/16 16:45 9/20 13:23
9/17 12:45 9/23 13:23
9/17 17:45 9/27 14:29
9/20 10:45 9/29 13:23

SQL

select start_time, max(process_time) 
from item 
group by date_format(start_time, '/%m/%d') 
order by start_time 
limit 1

解説

max(process_time)
max(カラム名)を使用すると最大値を取得できる。 
※min(カラム)を使用した場合は最小値を取得できる。

group by date_format(start_time, '/%m/%d')
group byを使用することで同一の開始日のデータをグループ分けをすることができる。
date_format(start_time, '/%m/%d')とすることで、時間を見ずに日付の部分だけでグループ分けができる。

order by start_time
group byで取得した中で開始日が最も古い順に並び替える。

limit 1
group byをすることにより複数件値が取れているが、1件しか欲しくないためlimit 1を使用し最初の行を取得する。
order byで並び替えていることによりlimit 1で欲しい行が取得できる。

参考ページ

上記、参考になれば幸いです。
もっと簡単に取得できる方法があれば教えていただきたいです!

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