LoginSignup
1
0

More than 5 years have passed since last update.

最新日付と過去の日付の差分を計算するSQL

Posted at

こんなテーブルから最新と過去の各日付の値を抜き出すSQLを書く

hogehoge_countsテーブル 日付と何かの数を持つテーブル
hogehoge_type 種別
date 日付
SELECT DISTINCT new.type,
    new.count 最新の数,
    old.count 過去日付の数,
    new.date 最新日付,
    old.date 過去日付,
    new.count - old.count 最新と過去の差分
FROM
(SELECT * FROM hogehoge_counts WHERE date = (SELECT max(date) FROM hogehoge_counts)) new
,
(SELECT * from hogehoge_counts WHERE date NOT IN (SELECT max(date) FROM hogehoge_counts)) old
WHERE new.hogehoge_type = old.hogehoge_type
ORDER BY old.date DESC, new.hogehoge_type;

FROM区のサブクエリで最新の日付と最新以外の日付を持つ値を引っ張ってそれを表示。

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