Snippets

VirtualWolf Daily highs and lows SQL query

Created by VirtualWolf last modified
SELECT extract(epoch from date)*1000 as timestamp, highest_timestamp, highest, lowest_timestamp, lowest FROM (
    WITH d AS (
        SELECT timestamp, temperature, date
        FROM weather_data
        WHERE sensor_id = (SELECT sensor_id FROM weather_sensors WHERE sensor_name = $1)
    )
    SELECT DISTINCT ON (date) date,
        last_value(timestamp) OVER w AS highest_timestamp,
        last_value(temperature) OVER w AS highest,
        first_value(timestamp) OVER w AS lowest_timestamp,
        first_value(temperature) OVER w AS lowest
    FROM d
    WINDOW w AS (
        PARTITION BY date ORDER BY temperature, timestamp
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
    )
    ORDER BY date DESC
    LIMIT 548
) t
ORDER BY timestamp ASC;
-- I did a few things to significantly speed up this query (about 40% faster!): 
--  - Changed the CTE to a subquery
--  - Added a compound index on (date, temperature, timestamp)
--  - Bumped Postgres' work_mem to 320MB

SELECT extract(epoch from date)*1000 as timestamp, highest_timestamp, highest, lowest_timestamp, lowest FROM (
    SELECT DISTINCT ON (date) date,
        last_value(timestamp) OVER w AS highest_timestamp,
        last_value(temperature) OVER w AS highest,
        first_value(timestamp) OVER w AS lowest_timestamp,
        first_value(temperature) OVER w AS lowest
    FROM (
        SELECT timestamp, temperature, date
        FROM weather_data
        WHERE sensor_id = (SELECT sensor_id FROM weather_sensors WHERE sensor_name = $1)
        AND temperature IS NOT NULL
    ) d
    WINDOW w AS (
        PARTITION BY date ORDER BY temperature, timestamp
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
    )
    ORDER BY date DESC
    LIMIT 548
) t
ORDER BY timestamp ASC;

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.