Per cominciare:la tua query attuale non fa quello che vuoi. Sembra che tu abbia effettivamente bisogno di una somma mensile su fix_costs
. Quindi partirei da:
select
sales_date,
country,
sum(sales_volume),
sum(sum(fix_costs)) over(partition by year(sales_date), month(sales_date))
/ day(last_day(sales_date))
as fix_cost_per_day
from sales
group by 1,2;
Questo produce:
sales_date | country | sum(sales_volume) | fix_cost_per_day :--------- | :------ | ----------------: | ---------------: 2020-01-03 | DE | 500 | 64.5161 2020-01-03 | FR | 350 | 64.5161 2020-01-03 | NL | 320 | 64.5161 2020-01-30 | None | 0 | 64.5161 2020-02-15 | DE | 700 | 172.4138 2020-02-15 | FR | 180 | 172.4138 2020-02-15 | NL | 420 | 172.4138 2020-02-29 | None | 0 | 172.4138 2020-03-27 | DE | 180 | 129.0323 2020-03-27 | FR | 970 | 129.0323 2020-03-27 | NL | 670 | 129.0323 2020-03-31 | None | 0 | 129.0323
Da lì in poi, puoi aggiungere la logica che tiene conto della "quota alle entrate giornaliere per paese". Da quanto ho capito la tua domanda, cioè:
select
sales_date,
country,
sum(sales_volume),
sum(sum(fix_costs)) over(partition by year(sales_date), month(sales_date))
/ day(last_day(sales_date))
* sum(sales_volume)
/ sum(sum(sales_volume)) over(partition by sales_date)
as fix_cost_per_day
from sales
group by 1,2;
Resi:
sales_date | country | sum(sales_volume) | fix_cost_per_day :--------- | :------ | ----------------: | ---------------: 2020-01-03 | DE | 500 | 27.57099531 2020-01-03 | FR | 350 | 19.29969672 2020-01-03 | NL | 320 | 17.64543700 2020-01-30 | None | 0 | null 2020-02-15 | DE | 700 | 92.83819629 2020-02-15 | FR | 180 | 23.87267905 2020-02-15 | NL | 420 | 55.70291777 2020-02-29 | None | 0 | null 2020-03-27 | DE | 180 | 12.76143212 2020-03-27 | FR | 970 | 68.76993974 2020-03-27 | NL | 670 | 47.50088621 2020-03-31 | None | 0 | null
Se necessario, puoi rimuovere i record per il paese 'None'
trasformando la query in una sottoquery e filtrando in una query esterna.