将某个特定月份的每月费用转换为每日费用

时间:2019-06-03 10:07:41

标签: mysql sql psql

我有一个包含原始数据的表,

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

成本是每个营销活动每月的总和。我需要做的是每天对它们进行计数(费用/(结束日期-开始日期) 并查看我每天的费用。

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....

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

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之间的数字表:

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

答案 1 :(得分:0)

在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 <>小提琴。

请注意,这会产生少量费用。如果要4.40:

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