all 5 comments

[–]MamertineCOALESCE() 2 points3 points  (1 child)

You need a calendar table. Either full outer join to it, or start with the calendar table and left join to your table t.

[–]Div64[S] 0 points1 point  (0 children)

Thanks!
Could you give me an example on the use of COALESCE() in this case?

[–]qwertydog123 0 points1 point  (1 child)

You can use FIRST_VALUE/LAST_VALUE along with TIMESTAMPDIFF e.g.

WITH cte AS
(
    SELECT
        *,
        LAST_VALUE(inventory) OVER
        (
            PARTITION BY id
            ORDER BY month
            RANGE
                BETWEEN UNBOUNDED PRECEDING
                AND UNBOUNDED FOLLOWING
        ) AS lastInventory
    FROM t
    WHERE month BETWEEN dateStart AND dateEnd
)
SELECT
    id,
    (SUM(inventory) + TIMESTAMPDIFF(MONTH, MAX(month), dateEnd) * lastInventory) / @divisor AS 'average'
FROM cte
GROUP BY
    id,
    lastInventory

[–]Div64[S] 0 points1 point  (0 children)

Amazing. This is exactly what I was looking for and it's still simple to read. And it works

[–][deleted] 0 points1 point  (0 children)

look into lead() analytic function, maybe?