我有一個簡單的 sqlite3 資料庫用于記錄溫度,資料庫架構非常簡單:-
CREATE TABLE temperatures (DateTime, Temperature);
要輸出超過 1 個月的最高和最低溫度,我有以下查詢:-
SELECT datetime, max(temperature), min(temperature) from temperatures
WHERE datetime(DateTime) > datetime('now', '-1 month')
GROUP BY strftime('%d-%m', DateTime)
ORDER BY DateTime;
我怎樣才能獲得最大值和最小值的時間?它是否需要子查詢或類似的東西?
uj5u.com熱心網友回復:
使用視窗函式MIN(),MAX()而FIRST_VALUE()不是聚合:
SELECT DISTINCT date(DateTime) date,
MAX(temperature) OVER (PARTITION BY date(DateTime)) max_temperature,
FIRST_VALUE(time(datetime)) OVER (PARTITION BY date(DateTime) ORDER BY temperature DESC) time_of_max_temperature,
MIN(temperature) OVER (PARTITION BY date(DateTime)) min_temperature,
FIRST_VALUE(time(datetime)) OVER (PARTITION BY date(DateTime) ORDER BY temperature) time_of_min_temperature
FROM temperatures
WHERE datetime(DateTime) > datetime('now', '-1 month')
ORDER BY date;
如果您的DateTime列包含 ISO 格式的值,YYYY-MM-DD hh:mm:ss則不需要datetime(DateTime).
可以直接使用DateTime。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/375473.html
上一篇:pythonsqlite字串比較
