I'm having problems to calculate the weighted average of a score, considering a windows of three months.
I would assign weight = 1 for the current row, weight of 0.5 for the previous month and weight of 0.33 for the last month of the time window. Then repeat the same logic for the second line which will have weight 1 the 2nd of 0.5 and so on..
I'm triyng with this query but it doesn't work like I would:
SELECT
anno,
mese,
id_lince,
score_s1_norm,
SUM(score_s1_norm * weight) OVER (PARTITION BY id_lince, anno ORDER BY anno DESC, mese DESC
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) /
SUM(weight) OVER (PARTITION BY id_lince, anno ORDER BY anno DESC, mese DESC
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS weighted_avg
FROM (
SELECT
anno,
mese,
id_lince,
score_s1_norm,
CASE
WHEN ROW_NUMBER() OVER (PARTITION BY id_lince, anno ORDER BY anno DESC, mese DESC) = 1 THEN 1
WHEN ROW_NUMBER() OVER (PARTITION BY id_lince, anno ORDER BY anno DESC, mese DESC) = 2 THEN 0.5
WHEN ROW_NUMBER() OVER (PARTITION BY id_lince, anno ORDER BY anno DESC, mese DESC) = 3 THEN 0.33
END AS weight
FROM lab.S1_cg14 d
) AS weighted_data
ORDER BY id_lince, anno DESC, mese DESC;
(https://i.stack.imgur.com/78xwT.png)
For example, the Weighted-AVG for the first line should be: SUM(Score * Weight)/SUM(Weight) (1 * 79.4 + 0.5 * 94.4 + 0.33 * 95.4) / (1 * 0.5 + 0.33) = 0.906
Thanks in advance to all who can help me