を発生し、温度およびタイムスタンプ、ミリ秒エポック時間で毎分1つのタイムスタンプのテーブル持っている最大値と最小値を取得し、タイムスタンプ:私が持っているのPostgres:彼らは私がPostgresの9.2を実行している
weather=# \d weather_data
Table "public.weather_data"
Column | Type | Modifiers
-------------+--------------+-----------
timestamp | bigint | not null
sensor_id | integer | not null
temperature | numeric(4,1) |
humidity | integer |
date | date | not null
Indexes:
"weather_data_pkey" PRIMARY KEY, btree ("timestamp", sensor_id)
"weather_data_date_idx" btree (date)
"weather_data_humidity_idx" btree (humidity)
"weather_data_sensor_id_idx" btree (sensor_id)
"weather_data_temperature_idx" btree (temperature)
"weather_data_time_idx" btree ("timestamp")
Foreign-key constraints:
"weather_data_sensor_id_fkey" FOREIGN KEY (sensor_id) REFERENCES weather_sensors(sensor_id)
weather=# select * from weather_data order by timestamp desc;
timestamp | sensor_id | temperature | humidity | date
---------------+-----------+-------------+----------+------------
1483272420000 | 2 | 22.3 | 57 | 2017-01-01
1483272420000 | 1 | 24.9 | 53 | 2017-01-01
1483272360000 | 2 | 22.3 | 57 | 2017-01-01
1483272360000 | 1 | 24.9 | 58 | 2017-01-01
1483272300000 | 2 | 22.4 | 57 | 2017-01-01
1483272300000 | 1 | 24.9 | 57 | 2017-01-01
[...]
をこの既存の毎日の高値と安値を取得するクエリが、その高いか低いが発生したことをない特定の時間:
WITH t AS (
SELECT date, highest, lowest
FROM (
SELECT date, max(temperature) AS highest
FROM weather_data
WHERE sensor_id = (SELECT sensor_id FROM weather_sensors WHERE sensor_name = 'outdoor')
GROUP BY date
ORDER BY date ASC
) h
INNER JOIN (
SELECT date, min(temperature) AS lowest
FROM weather_data
WHERE sensor_id = (SELECT sensor_id FROM weather_sensors WHERE sensor_name = 'outdoor')
GROUP BY date
ORDER BY date ASC
) l
USING (date)
ORDER BY date DESC
)
SELECT * from t ORDER BY date ASC;
の2つのがあり万行を超えるビットは、データベース内だと、それは〜1.2秒かかります実行する 残念な。私は今、高いか低いがあったことを特定の時刻を取得したい、私はが作業を行い、この使用してウィンドウ関数、思い付いたけど〜5.6秒かかる:
SELECT h.date, high_time, high_temp, low_time, low_temp FROM (
SELECT date, high_temp, high_time FROM (
SELECT date, temperature AS high_temp, timestamp AS high_time, row_number()
OVER (PARTITION BY date ORDER BY temperature DESC, timestamp DESC)
FROM weather_data
WHERE sensor_id = (SELECT sensor_id FROM weather_sensors WHERE sensor_name = 'outdoor')
) highs
WHERE row_number = 1
) h
INNER JOIN (
SELECT * FROM (
SELECT date, temperature AS low_temp, timestamp AS low_time, row_number()
OVER (PARTITION BY date ORDER BY temperature ASC, timestamp DESC)
FROM weather_data
WHERE sensor_id = (SELECT sensor_id FROM weather_sensors WHERE sensor_name = 'outdoor')
) lows
WHERE row_number = 1
) l
ON h.date = l.date
ORDER BY h.date ASC;
をするいくつかの比較的単純な加算があります私はそれが実行時間の大量を追加しません作ることができる最初のクエリ?私はそこにあると仮定しますが、私は私が問題をあまりにも長く見ていた時点にいると思います!
可能重複タイブレーカとして順序にZTIMESTAMP添加Z日付とZタイムスタンプ
無関係ですが、最初のクエリの派生テーブルの 'order by 'は無駄です –
@a_horse_with_no_name注目、ありがとう! – VirtualWolf