简体   繁体   中英

Distribute costs by day between a given StartDate and EndDate using BigQuery SQL

My table shows the total budget of marketing campaigns for a given period:

Campaign Name StartDate EndDate Budget (total)
Campaign-1 2023-01-01 2023-01-04 100 €
Campaign-2 2023-01-15 2023-01-21 210 €

I would like to distribute the total budget per campaign linearly over the days.

Therefore, the result should look like this:

Campaign Name Date Budget (daily)
Campaign-1 2023-01-01 25 €
Campaign-1 2023-01-02 25 €
Campaign-1 2023-01-03 25 €
Campaign-1 2023-01-04 25 €
Campaign-2 2023-01-15 30 €
Campaign-2 2023-01-16 30 €
Campaign-2 2023-01-17 30 €
Campaign-2 2023-01-18 30 €
Campaign-2 2023-01-19 30 €
Campaign-2 2023-01-20 30 €
Campaign-2 2023-01-21 30 €

I've come across GENERATE_DATE_ARRAY. However, splitting the budget out to a single date per row has been the hard part.

SELECT period
FROM (SELECT MIN(CAST(StartDate AS DATE)) as min_date,
             MAX(CAST(EndDate)) as max_date
      FROM total_budget
     ) tb JOIN
     UNNEST(GENERATE_DATE_ARRAY(tb.min_date, tb.max_date)) period

Would be glad about help!

You may consider below approach.

WITH sample_table AS (
  SELECT 'Campaign-1' campaign_name, DATE '2023-01-01' start_date, DATE'2023-01-04' end_date, 100 budget_total UNION ALL
  SELECT 'Campaign-2' campaign_name, '2023-01-15', '2023-01-21', 210
)
SELECT campaign_name, date, budget_total / (DATE_DIFF(end_date, start_date, DAY) + 1) AS budget_daily
  FROM sample_table, UNNEST(GENERATE_DATE_ARRAY(start_date, end_date)) date;

Query results

在此处输入图像描述

Consider also below approach

select campaign_name, date, 
  budget_total / count(*) over(partition by campaign_name) as budget_daily
from your_table, unnest(generate_date_array(start_date, end_date)) date        

if applied to sample data in your question - output is

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM