[英]BigQuery: Split monthly data into days
我想從現有數據創建一個新表:
日期 | 店鋪 | 成本 |
---|---|---|
2022-01-10 | 一種 | 3000 |
2022-01-10 | b | 2500 |
最后目標表應該是這樣的:
日期 | 店鋪 | 成本 |
---|---|---|
2022-01-10 | 一種 | 96,77 |
2022-02-10 | 一種 | 96,77 |
2022-03-10 | 一種 | 96,77 |
2022-04-10 | 一種 | 96,77 |
....到本月的最后一天 | 一種 | 96,77 |
2022-01-10 | b | 80,65 |
2022-02-10 | b | 80,65 |
2022-03-10 | b | 80,65 |
... | b | 80,65 |
該查詢應插入到另一個 bigquery 表中,其中包含每個月的每一天的新行(如第二個表)。 成本應除以每月的日期以分攤成本。
我嘗試了一些查詢,但找不到解決方案::(
謝謝!
在這里使用這個答案,我計算了每個月的天數,然后我用它除以每月成本得到daily_avg_monthly_cost
。 然后我加入了一個數組生成的表,其中包含一年中每個月的所有日期,並得到了最終的 output。
請注意:此解決方案的局限性在於值“2022”是硬編碼的。
WITH source_data as (
SELECT date('2022-01-10') as _month, 'a' as store, 3000 as cost
UNION ALL
SELECT date('2022-01-10') as _month, 'b' as store, 2500 as cost
UNION ALL
SELECT date('2022-02-10') as _month, 'a' as store, 4000 as cost
UNION ALL
SELECT date('2022-02-10') as _month, 'b' as store, 3500 as cost
), cost_table AS (
SELECT
FORMAT_DATE('%Y-%m', _month) AS month,
store,
cost/EXTRACT(DAY FROM (DATE_SUB(DATE_TRUNC(DATE_ADD(_month, INTERVAL 1 MONTH), MONTH),INTERVAL 1 DAY))) daily_avg_monthly_cost
FROM source_data
),days AS (
SELECT
d,
FORMAT_DATE('%Y-%m',d) AS month
FROM (
SELECT
*
FROM
UNNEST(GENERATE_DATE_ARRAY('2022-01-01', '2022-12-31', INTERVAL 1 DAY)) AS d
)
)
SELECT
days.d as date,
cost_table.store,
cost_table.daily_avg_monthly_cost
FROM cost_table
JOIN days ON CAST(cost_table.month AS STRING) = days.month
您也可以考慮以下內容。
WITH sample_table AS (
SELECT '2022-01-10' date, 'a' store, 3000 cost UNION ALL
SELECT '2022-01-10' date, 'b' store, 2500 cost
)
SELECT store, date, ROUND(cost / COUNT(1) OVER (PARTITION BY store, _date), 2) cost
FROM (
SELECT store, cost,
-- parse *date* STRING to DATE type
PARSE_DATE('%Y-%d-%m', date) AS _date,
FROM sample_table
), UNNEST(GENERATE_DATE_ARRAY(DATE_TRUNC(_date, MONTH), LAST_DAY(_date))) date;
查詢結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.