我有以下的PostgreSQL的代碼(其中工程,但慢慢地),這我使用創建一個物化視圖,但它是相當緩慢和代碼長度似乎與多繁瑣子查詢。無論如何,我可以提高此代碼在執行或重寫時的速度,因此它更短且更易於維護?我可以加快這一嵌套子查詢PostgreSQL的查詢
CREATE MATERIALIZED VIEW station_views.obs_10_min_avg_ffdi_powerbi AS
SELECT t.station_num,
initcap(t.station_name) AS station_name,
t.day,
t.month_int,
to_char(to_timestamp(t.month_int::text, 'MM'), 'TMMonth') AS Month,
round(((date_part('year', age(t2.dmax, t2.dmin)) * 12 + date_part('month', age(t2.dmax, t2.dmin)))/12)::numeric, 1) AS record_years,
round((t2.count_all_vals/t2.max_10_periods * 100)::numeric, 1) AS per_datset,
max(t.avg_bom_fdi) AS max,
avg(t.avg_bom_fdi) AS avg,
percentile_cont(0.95) WITHIN GROUP (ORDER BY t.avg_bom_fdi) AS percentile_cont_95,
percentile_cont(0.99) WITHIN GROUP (ORDER BY t.avg_bom_fdi) AS percentile_cont_99
FROM (SELECT a.station_num,
d.station_name,
a.ten_minute_intervals_utc,
date_part('day', a.ten_minute_intervals_utc) AS day,
date_part('month', a.ten_minute_intervals_utc) AS month_int,
a.avg_bom_fdi
FROM analysis.obs_10_min_avg_ffdi_bom a,
obs_minute_stn_det d
WHERE d.station_num = a.station_num) t,
(SELECT obs_10_min_avg_ffdi_bom_view.station_num,
obs_10_min_avg_ffdi_bom_view.station_name,
min(obs_10_min_avg_ffdi_bom_view.ten_minute_intervals_utc) AS dmin,
max(obs_10_min_avg_ffdi_bom_view.ten_minute_intervals_utc) AS dmax,
date_part('epoch', max(obs_10_min_avg_ffdi_bom_view.ten_minute_intervals_utc) - min(obs_10_min_avg_ffdi_bom_view.ten_minute_intervals_utc))/600 AS max_10_periods,
count(*) AS count_all_vals
FROM analysis.obs_10_min_avg_ffdi_bom_view
GROUP BY obs_10_min_avg_ffdi_bom_view.station_num, obs_10_min_avg_ffdi_bom_view.station_name) t2
WHERE t.station_num = t2.station_num
GROUP BY t.station_num, t.station_name, Month, t.month_int, t.day, record_years, per_datset
ORDER BY t.month_int, t.day
WITH DATA;
輸出我得到的是與天&月一個天氣變量記錄(avg_bom_fdi)沿着每個氣象站行(station_num & STATION_NAME)。月份值將保留並轉換爲名稱,以繪製圖表上每月平均值的值。我也拉的,對於該站(record_years)以及該數據集是如何完成的(per_datset)的百分比存在的記錄總數年化。這些都來自第二個子查詢(t2)。第一個子查詢(t)用於平均每天的數據並返回每日最大值,平均值和95/99百分位數。
不包括order by子句。訂單數據存儲在表中,或物化視圖不相關。最終輸出只有otder數據。 –