将具有不同条件的不同频率的2个时间序列表联接起来

时间:2019-04-13 09:16:28

标签: sql postgresql join time-series

我正在尝试将具有每日数据的表与具有季度或更长频率数据的表联接,并在ID和日期上进行匹配。我相信我需要一个完整的外部加入例如我需要所有按日期排列的每日数据和季度数据,如果没有可用的季度数据,则为空。

这是我到目前为止尝试过的:

select daily.id, daily.date, daily.value as dly_value, quarterly.value as qly_value
from daily
full outer join quarterly on daily.id = quarterly.id
and daily.date = quarterly.date
where daily.type = 'dly_type'
and quarterly.type = 'qly_type'
and daily.id = 16

但这仅返回与季度日期匹配的行。如果我省略了与日期匹配的行,则将获取所有的每日数据,加上季度数据,但未按日期对齐。

很明显,我缺少明显的东西,但是我显然没有以正确的方式向Google问这个问题!

2 个答案:

答案 0 :(得分:1)

您描述的是left join,而不是full join-所有具有季度匹配值的每日数据:

select d.id, d.date, d.value as dly_value, q.value as qly_value
from daily d left join
     quarterly q
     on d.id = q.id and
        d.date = q.date and
        q.type = 'qly_type'
where d.type = 'dly_type' and
      d.id = 1;  -- this is suspicious.  Doesn't this match only one daily row?

您的加入条件可疑。您为什么同时加入iddate?我想这是否是您问题的根源。因此,我怀疑您确实想要:

select d.id, d.date, d.value as dly_value, q.value as qly_value
from daily d left join
     quarterly q
     on d.date = q.date and
        q.type = 'qly_type'
where d.type = 'dly_type';

Full join几乎不需要。如果确实需要它并且要过滤两个表,则建议在子查询中过滤:

select d.id, d.date, d.value as dly_value, q.value as qly_value
from (select d.*
      from daily d
      where d.type = 'dly_type' and
            d.id = 1
     ) d full join
     (select q.*
      from quarterly q
      where q.type = 'qly_type'
     ) q
     on d.id = q.id and
        d.date = q.date

答案 1 :(得分:0)

这将起作用:

select daily.id, daily.date, daily.value as dly_value, quarterly.value as qly_value
from daily
full outer join quarterly on daily.id = quarterly.id
and date_trunc('DAY',daily.date) = date_trunc('DAY',quarterly.date)
where daily.type = 'dly_type'
and quarterly.type = 'qly_type'
and daily.id = 16