我跑的Postgres 9.2,並有溫度和時間標記,每分鐘一個時間戳毫秒時代時間的表:Postgres的:獲得最大值和最小值,和時間戳他們發生
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;
有一點超過兩個百萬行的數據庫,它需要〜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;
有一些相對簡單的除我可以做的第一個查詢不會增加大量的執行時間?我假設有,但我認爲我處於這個問題太久的地步了!
[的PostgreSQL可能的複製 - 獲取行具有最大值的列](http://stackoverflow.com/questions/586781/postgresql-fetch-the-row-which-has-the-max-value- for-a-column) – Joe
不相關,但是:第一個查詢中派生表中的「order by」無用 –
@a_horse_with_no_name注意,謝謝! – VirtualWolf