简体   繁体   English

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

[英]Transform sql code to bigquery sql (eomonth)

I want to split my monthly Values in daily values.我想将我的每月值拆分为每日值。 The monthly value also split by the number of days of the month.每月值也除以该月的天数。 I found a SQL query but I cant apply the query in Bigquery.我找到了一个 SQL 查询,但我无法在 Bigquery 中应用该查询。 How can I apply this query in BigQuery?如何在 BigQuery 中应用此查询? Are there any options instead of eomonth?有什么选项可以代替 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    
 
  
   

Thanks!谢谢!

last_day is the Bigquery function equivalent of eomonth . last_day是相当于 eomonth 的eomonth

Bigquery's generate_date_array is a better solution than the recursive CTE in your example. Bigquery 的generate_date_array是比您示例中的递归 CTE 更好的解决方案。 Which is lucky as Bigquery does not support recursive CTEs.这很幸运,因为 Bigquery 不支持递归 CTE。

Here's the answer:这是答案:

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

The CTE is just for example data. CTE 只是示例数据。 generate_date_array gives an array which we unnest into rows. generate_date_array给出了一个array ,我们将其unnest到行中。 That happens in the from clause with a cross join as there is no join criteria, other than parameters to the function.这发生在带有cross joinfrom子句中,因为除了 function 的参数之外,没有连接标准。

The "units" calculation is weird in the initial example.在初始示例中,“单位”计算很奇怪。 extract(day from days) gives the day of the month as an int64 , which is what the original does. extract(day from days)int64形式给出月份中的某一天,这是原始版本所做的。

@Steven Ensslen @史蒂文恩斯伦

thank you!谢谢你!

date日期 store店铺 cost成本
2022-01-10 2022-01-10 a一个 3000 3000
2022-01-10 2022-01-10 b b 2500 2500

And finally the targettable should look like:最后目标表应如下所示:

date日期 store店铺 cost成本
2022-01-10 2022-01-10 a一个 3000/sum day of months = 96,77 3000/月总天数 = 96,77
2022-02-10 2022-02-10 a一个 3000/sum day of months 3000/月总和
2022-03-10 2022-03-10 a一个 3000/sum day of months 3000/月总和
2022-04-10 2022-04-10 a一个 3000/sum day of months 3000/月总和
.... to last day of the month ....到本月的最后一天 a一个 3000/sum day of months 3000/月总和
2022-01-10 2022-01-10 b b 2500/sum day of months 2500/月总和
2022-02-10 2022-02-10 b b 2500/sum day of months 2500/月总和
2022-03-10 2022-03-10 b b 2500/sum day of months 2500/月总和
... ... b b 2500/sum day of months 2500/月总和

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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