我正在使用 Postgres 9.1,我有一个查询返回 2 列,即使没有数据存在,我也希望复制这些列。我的查询的重要部分是
SELECT DATE_TRUNC('week', tx_dttm) AS interval_time, institution_id FROM (...)
WHERE institution_id IN (1, 3, 4, 5, 7, 9) GROUP BY interval_time, institution_id
正如我所期望的那样,这将返回给我所有机构和所有 interval_times。现在我也想要没有数据的行。我可以执行以下操作来一次获取任何一个
SELECT DATE_TRUNC('week', tx_dttm) AS interval_time, institution_id FROM (...)
WHERE institution_id IN (1, 3, 4, 5, 7, 9) GROUP BY interval_time, institution_id
RIGHT JOIN generate_series('2012-02-03', '2013-02-18', interval '1 week')
ON DATE_TRUNC('week', generate_series) = interval_time
或者
SELECT DATE_TRUNC('week', tx_dttm) AS interval_time, institution_id FROM (...)
WHERE institution_id IN (1, 3, 4, 5, 7, 9) GROUP BY interval_time, institution_id
RIGHT JOIN unnest(array[1, 3, 4, 5, 7, 9]) AS all_institution_id
ON all_institution_id = institution_id
但是,我想将它们结合起来,以便获得所有机构的所有 interval_times。似乎最好的办法是创建某种中间表,其中包含为每个 interval_time 重复的每个机构 ID,然后在其上进行 RIGHT JOIN,但我不知道该怎么做。任何帮助将非常感激。
编辑
玩了一会儿之后,我想做的似乎是以下,但我的语法是错误的
SELECT DATE_TRUNC('week', tx_dttm) AS interval_time, institution_id FROM (...)
WHERE institution_id IN (1, 3, 4, 5, 7, 9) GROUP BY interval_time, institution_id
RIGHT JOIN unnest(array[1, 3, 4, 5, 7, 9]) AS all_institution_id,
generate_series('2012-02-03', '2013-02-18', interval '1 week')
ON DATE_TRUNC('week', generate_series) = dose_hsts.interval_time
AND all_institution_id = institution_id