将每月成本转换为某个特定月份的每日成本

Transform Monthly Costs to the cost on daily basis for some particular month

我有一个 table,原始数据如下:

campaign costs   start_date end_date
brand    132.25  2019-04-01 2019-04-30
brand    155.25  2019-05-01 2019-05-31

成本是每个营销活动按月计算的总和。我需要做的是每天计算它们 (Costs/(End_date-start_date) 并查看我每天看到的费用。

campaign costs   Date
brand   4.40    2019-04-01
brand   4.40    2019-04-02
brand   4.40    2019-04-03
brand   4.40    2019-04-04
brand   4.40    2019-04-05....

如有任何帮助,将不胜感激。

MySQL 8 起:

with DATES as
(
select campaign, start_date as thedate
from Mytable
union all
select campaign, date_add(start_date, interval 1 day) 
from DATES
where thedate < end_date
)
select t1.*, costs/datediff(end_date, start_date) as newcosts
from DATES t1
left join MyTable t2
on t2.campaign = t1.campaign
and thedate between start_date and end_date

前 MySQL 8:

从 0 到 30 填充数字 table:

create table Numbers (NN integer);

Insert into Numbers (NN) values (1),(2),...,(30);

现在使用它:

select t1.*, t2.costs/datediff(t2.end_date, t2.start_date) as newcosts
from
(
select campaign, date_add(start_date, Interval NN day) as Thedate
from MyTable 
cross join Numbers
where date_add(start_date, Interval NN day) <= end_date
) t1
left join MyTable t2
on t1.TheDate between t2.start_date and t2.end_date

在 Postgres 中,您只需执行以下操作:

select t.campaign,
       t.costs / (t.end_date - t.start_date + 1),
       gs.dte
from t cross join
     generate_series(start_date, end_date, interval '1 day') gs(dte);

Here 是一个 db<>fiddle.

请注意,这会产生一小部分费用。如果你想要 4.40:

round(t.costs / (t.end_date - t.start_date + 1) - 0.005, 2),