Get the last know value for a specific reference in inconsistent timeline

Viewed 33

I'm trying to get records from the stats table and if there is no data for the specific day and reference get the latest known value for a given ref.

stats table:

| ref | date     | views |
| --- | -------- | ----- |
| 1   |2022-01-01|1      |
| 2   |2022-01-01|1      |
| 1   |2022-01-02|2      |
| 2   |2022-01-02|1      |
| 1   |2022-01-03|2      |
| 1   |2022-01-04|3      |
| 2   |2022-01-04|3      |

As you see above there the record for ref 2 at 2022-01-03 is missing. Now I want to sum views for those records and group them by the ref column and since there is one missing record for ref 2 the value for the summation should be taken from the latest record (2022-01-02).

I have also the posts table:

| id  | title     |
| --- | --------- |
| 1   |title no. 1|
| 2   |title no. 2|

Also, I have to create a timeline from the oldest stat to the current date. What do I have is:

WITH RECURSIVE timeline (
    date
) AS (
    SELECT
        MIN(date)
    FROM
        stats
UNION ALL
SELECT
    DATE_ADD(date, INTERVAL 1 day)
FROM
    timeline
WHERE (timeline.date < CURRENT_DATE),

posts_days AS (
    SELECT timeline.date, posts.id
    FROM
        posts
    CROSS JOIN timeline
),

view_stats AS (
    SELECT posts_days.date, posts_days.id, stats.views
    FROM
        posts_days
    LEFT JOIN stats ON  (stats.ref = posts_days.id and stats.date = posts_days.date)
)

SELECT
    view_stats.date, SUM(view_stats.views) AS views
--  ,SUM(prev_stats.views) AS prev_views, 
FROM view_stats
LEFT JOIN (
        SELECT id, (view_stats.views) as views, date FROM view_stats GROUP BY id, date
    ) as prev_stats on prev_stats.date = (
      SELECT date FROM view_stats s1 
        WHERE s1.date < view_stats.date and s1.id = view_stats.id ORDER BY date desc limit 1
    ) and prev_stats.id = view_stats.id
GROUP BY date
ORDER BY date

But it obviously behaves in the wrong way. I would be appreciated any tips on how to solve this one.

0 Answers
Related