我正在尝试在 postgres 中组合两个交叉表,但卡住了,如果有人指导我,那就太好了。
-- rainfall CROSS TAB
SELECT * FROM
CROSSTAB(
'SELECT block_id, forecast_date, rainfall_mm
FROM weather.imd_forecast
ORDER BY 1'
)
AS rainfall_crosstab(
block_id int, rainfall_day_1 numeric, rainfall_day_2 numeric,
rainfall_day_3 numeric, rainfall_day_4 numeric, rainfall_day_5 numeric
);
-- temp_max CROSS TAB
SELECT * FROM
CROSSTAB(
'SELECT block_id, forecast_date, temp_max_deg_c
FROM weather.imd_forecast
ORDER BY 1'
)
AS temp_max_crosstab(
block_id int, temp_max_day_1 numeric, temp_max_day_2 numeric,
temp_max_day_3 numeric, temp_max_day_4 numeric, temp_max_day_5 numeric);
假设 block_id 和 Forecast_date 是两个交叉表结果中的公共字段,您可以
join
根据这些字段使用操作来组合它们。基于该假设,首先,我们可以使用公用表表达式 (CTE) 为 rainoff_crosstab 和 temp_max_crosstab 创建临时结果集。然后,我们对block_id
和forecast_date
字段执行 JOIN 操作以合并两个交叉表结果。您的两个查询都需要
ORDER BY 1, 2
,而不仅仅是ORDER BY 1
. 否则结果可能是错误的。请参阅小提琴中的演示。组合解决方案:
小提琴
在这里阅读: