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?

More than 5 years have passed since last update.

PostgreSQLで「昨年のデータ」と「現在のデータ」を並べて表示

1
Last updated at Posted at 2020-01-03

扱うデータ

気温(℃)のデータが、下記のように30分間隔で格納されている

  • meas_dt : 計測時刻
  • temperature : 気温
SELECT meas_dt, temperature
FROM thermo_data
ORDER BY meas_dt DESC;

(出力結果)
       meas_dt       | temperature 
---------------------+-------------
 2020-01-03 17:30:00 |        9.70
 2020-01-03 17:00:00 |       10.51
 2020-01-03 16:30:00 |       11.07
 2020-01-03 16:00:00 |       11.59
 2020-01-03 15:30:00 |       11.52
 2020-01-03 15:00:00 |       11.40
 2020-01-03 14:30:00 |       11.50
...

やりたいこと

「昨年(2019年)の同じ時刻の気温」を表す列を新たに追加して、同じ行に表示させたい。
以下がやりたいイメージ

SELECT meas_dt, temperature, (昨年の気温)
FROM thermo_data
ORDER BY meas_dt DESC;

(出力結果)
       meas_dt       | temperature | (昨年の気温)
---------------------+-------------+-------------
 2020-01-03 17:30:00 |        9.70 |     7.67
 2020-01-03 17:00:00 |       10.51 |     8.29
 2020-01-03 16:30:00 |       11.07 |     8.30
 2020-01-03 16:00:00 |       11.59 |     9.79
 2020-01-03 15:30:00 |       11.52 |     9.84
 2020-01-03 15:00:00 |       11.40 |    10.70
 2020-01-03 14:30:00 |       11.50 |    11.00
...

相関サブクエリを使って解決

以下のSQL文を作ると、昨年の気温を並べて出力可能!

SELECT meas_dt, temperature,
       -- 相関サブクエリ。テーブルの別名を「T2」とする
       (SELECT temperature
        FROM thermo_data AS T2
        -- 「昨年の気温」を出力を実現するための制約条件
        WHERE T2.meas_dt = T1.meas_dt + interval '-1 year'
       ) AS temp_lastyear
FROM thermo_data AS T1 -- メインクエリのテーブルの別名は「T1」とする
ORDER BY meas_dt DESC;

(出力結果)
       meas_dt       | temperature | temp_lastyear
---------------------+-------------+--------------
 2020-01-03 17:30:00 |        9.70 |      7.67
 2020-01-03 17:00:00 |       10.51 |      8.29
 2020-01-03 16:30:00 |       11.07 |      8.30
 2020-01-03 16:00:00 |       11.59 |      9.79
 2020-01-03 15:30:00 |       11.52 |      9.84
 2020-01-03 15:00:00 |       11.40 |     10.70
 2020-01-03 14:30:00 |       11.50 |     11.00
...
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?