【问题标题】:Getting a Monthly Date Range获取每月日期范围
【发布时间】:2021-12-06 23:23:27
【问题描述】:

如何在大查询中创建日期范围?日期范围从当月 29 日开始,到下个月 28 日结束。应该是这样的

日期 |开始日期 |结束日期

2020 年 3 月 13 日 | 2020 年 2 月 29 日 | 03-28-2021

2020 年 6 月 30 日 | 2020 年 6 月 29 日 | 07-28-2021

01-01-2021 | 2020 年 12 月 29 日 | 01-28-2021

2021 年 11 月 11 日 | 2021 年 10 月 28 日 | 2021 年 11 月 29 日

其实,我写了一篇关于它的文章。 看看这个:

https://www.theaccountingtactics.com/2021/12/BigQueryBQ-DateProblems-DateSituations-that-are-Hard-to-Analyze-and-Takes-Time-ToCrack%20.html?m=1

【问题讨论】:

  • 3 月的大多数日期会发生什么,通常没有 2 月 29 日开始?
  • 另外,最好删除文章的链接并将表格粘贴到您的问题中。
  • 我已经编辑了这个问题。我不知道如何创建表格。
  • 如果是闰年,则指向2021年3月1日

标签: sql google-bigquery


【解决方案1】:

考虑以下方法

create temp function set_day(date date, day int64) as (
  ifnull(
    safe.date(extract(year from date), extract(month from date), day), 
    last_day(date)
  )
);
select Date, 
  set_day(Starting_Date, 29) as Starting_Date,
  set_day(Ending_Date, 28) as Ending_Date
from (
  select *, if(extract(day from Date) < 29, 
      struct(date_sub(Date, interval 1 month) as Starting_Date, Date as Ending_Date),
      struct(Date as Starting_Date, date_add(Date, interval 1 month) as Ending_Date)
    ).*
  from your_table 
)
     

如果应用于您的问题中的示例数据

with your_table as (
  select date '2020-03-13' Date union all
  select '2021-03-13' union all
  select '2020-06-30' union all
  select '2021-01-01' union all
  select '2021-11-11' 
)            

输出是

你可以用下面的方法测试整个东西

create temp function set_day(date date, day int64) as (
  ifnull(
    safe.date(extract(year from date), extract(month from date), day), 
    last_day(date)
  )
);
with your_table as (
  select date '2020-03-13' Date union all
  select '2021-03-13' union all
  select '2020-06-30' union all
  select '2021-01-01' union all
  select '2021-11-11' 
) 
select Date, 
  set_day(Starting_Date, 29) as Starting_Date,
  set_day(Ending_Date, 28) as Ending_Date
from (
  select *, if(extract(day from Date) < 29, 
      struct(date_sub(Date, interval 1 month) as Starting_Date, Date as Ending_Date),
      struct(Date as Starting_Date, date_add(Date, interval 1 month) as Ending_Date)
    ).*
  from your_table 
)

【讨论】:

  • 我尝试将您的查询复制并粘贴到 Google Cloud Platform 上。这是一个错误。我不熟悉您的某些功能。对此道歉..我只是 Big Query 的初学者。
  • 我添加了整个测试代码 - 再试一次,如果仍有问题,请告诉我
  • 哇。它现在正在工作,但我不知道某些功能的用法。我也查询了它,但它比你的要长。链接:theaccountingtactics.com/2022/01/… 无论如何,谢谢..
猜你喜欢
  • 2020-11-10
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多