按比例在bigquery中

9rnv2umw  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(394)

这个问题在这里已经有答案了

sql按行平均分配值(2个答案)
bigquery中的do循环(1个答案)
15小时前关门了。
我想按比例给这样一张table打分:

在这样一张table上:

基本上我想为date\u start和date end之间的天数创建行,然后用花费除以有多少天。
我目前正在使用下面的查询来完成这项工作,使用bigquery脚本-我知道这可能是一种可怕的查询方式,但我不知道还能怎么做。仅运行3行查询需要大约30秒。

DECLARE i INT64 DEFAULT 1;

DECLARE n int64;

SET n = (SELECT COUNT(*) FROM `pro_rata_test.data`);

DELETE FROM `pro_rata_test.pro_rata` WHERE TRUE;

WHILE i <= n DO
INSERT INTO
  pro_rata_test.pro_rata
SELECT
  day,
  country,
  campaign,
  other,
  SUM(spend)/(
  SELECT
    DATETIME_DIFF(DATETIME(TIMESTAMP(date_end)),
      DATETIME(TIMESTAMP(date_start)),
      DAY) + 1
  FROM (
    SELECT *, ROW_NUMBER() OVER(ORDER BY date_start) AS rn FROM `pro_rata_test.data`)
  WHERE
    rn = i) AS spend
FROM (
  SELECT *, ROW_NUMBER() OVER(ORDER BY date_start) AS rn FROM `pro_rata_test.data`),
  UNNEST(GENERATE_DATE_ARRAY(date_start, date_end)) day
WHERE
  rn = i
GROUP BY
  day,
  country,
  campaign,
  other
ORDER BY
  day;

SET
  i = i + 1;

END WHILE
eqqqjvef

eqqqjvef1#

尝试 generate_date_array 以及 unnest :

with mytable as (
  select date '2021-01-01' as date_start, date '2021-01-10' as date_end, 100 as spend, 'FR' as country, 'Campaign1' as campaign, 'test1' as Other union all
  select date '2021-01-11', date '2021-02-27', 150, 'UK', 'Campaign1', 'test2' union all
  select date '2021-03-20', date '2021-04-20', 500, 'UK', 'Campaign2', 'test2'
)
select
  day,
  country,
  campaign,
  other,
  spend/(date_diff(date_end, date_start, day)+1) as spend
from mytable, unnest(generate_date_array(date_start, date_end)) as day
order by day

相关问题