I'm trying to sum values inside a window function but I can't figure out have to prevent summing duplicates. Below is a snippet of the results I have right now. For the last column I want to calculate REG_MOVEMENT summed across unique STORE_ID's and then divide it by the number of unique stores. This column should be 5603.5 ((9359 + 1848)/2) since there are 3 rows with the same STORE_ID and one different.
| KEY_ID | PRODUCT_ID | STORE_ID | REG_MOVEMENT | (No column name) |
|---|---|---|---|---|
| 154 | 5214266 | 28002 | 9359 | 7481.25 |
| 155 | 5214266 | 28002 | 9359 | 7481.25 |
| 156 | 5214266 | 28002 | 9359 | 7481.25 |
| 173 | 5214266 | 28005 | 1848 | 7481.25 |
My current code is
SELECT
KEY_ID,
PRODUCT_ID,
STORE_ID,
REG_MOVEMENT,
SUM(REG_MOVEMENT) OVER(PARTITION BY PRODUCT_ID) / CONUT(STORE_ID) OVER(PARTITION BY PRODUCT_ID)