Efficient time series querying in Postgres

前端 未结 4 1797
逝去的感伤
逝去的感伤 2020-12-30 13:05

I have a table in my PG db that looks somewhat like this:

id | widget_id | for_date | score |

Each referenced widget has a lot of these ite

4条回答
  •  礼貌的吻别
    2020-12-30 13:36

    SQL Fiddle

    select
        widget_id,
        for_date,
        case
            when score is not null then score
            else first_value(score) over (partition by widget_id, c order by for_date)
            end score
    from (
        select
            a.widget_id,
            a.for_date,
            s.score,
            count(score) over(partition by a.widget_id order by a.for_date) c
        from (
            select widget_id, g.d::date for_date
            from (
                select distinct widget_id
                from score
                ) s
                cross join
                generate_series(
                    (select min(for_date) from score),
                    (select max(for_date) from score),
                    '1 day'
                ) g(d)
            ) a
            left join
            score s on a.widget_id = s.widget_id and a.for_date = s.for_date
    ) s
    order by widget_id, for_date
    

提交回复
热议问题