将 sql 代码转换为 bigquery sql (eomonth)



我想将每月值拆分为每日值。每月值也除以月份的天数。我找到了一个 SQL 查询,但我无法在 Bigquery 中应用该查询。 如何在 BigQuery 中应用此查询?除了 eomonth,还有什么选择吗?

with cte as
(
select 
targetdate, 
eomonth(targetdate) enddate, 
1.0 * units / day(eomonth(targetdate)) units
from targettable
union all
select dateadd(day, 1, targetdate), enddate, units 
from cte
where targetdate < enddate ) 
select targetdate, units from cte    



谢谢!

last_day是相当于eomonth的Bigquery函数。

Bigquery 的generate_date_array是比示例中的递归 CTE 更好的解决方案。这很幸运,因为 Bigquery 不支持递归 CTE。

答案如下:

with targettable as (
SELECT date('2022-01-10') as targetdate, 31 as units
)
select days,
last_day(targettable.targetdate) enddate,
units / extract(day from days) as units
from targettable
cross join unnest(generate_date_array(targettable.targetdate, last_day(targettable.targetdate))) as days

CTE 只是示例数据。generate_date_array给出了一个array,我们将其unnest成行。 这发生在带有cross joinfrom子句中,因为除了函数的参数之外,没有连接条件。

在最初的示例中,"单位"计算很奇怪。extract(day from days)给出了月份中的某一天作为int64,这就是原版所做的。

最新更新