Populating a table with all dates in a given range in Google BigQuery

前端 未结 2 1904
说谎
说谎 2020-12-14 10:50

Is there any convenient way to populate a table with all dates in a given range in Google BigQuery? What I need are all dates from 2015-06-01 till CURRENT_DATE(), so somethi

相关标签:
2条回答
  • 2020-12-14 11:04

    Mikhail's answer works for BigQuery's legacy sql syntax perfectly. This solution is a slightly easier one if you're using the standard SQL syntax.

    BigQuery standard SQL syntax actually has a built in function, GENERATE_DATE_ARRAY for creating an array from a date range. It takes a start date, end date and INTERVAL. For example:

    SELECT day
    FROM UNNEST(
        GENERATE_DATE_ARRAY(DATE('2015-06-01'), CURRENT_DATE(), INTERVAL 1 DAY)
    ) AS day
    

    If you wanted the week and year you could use

    SELECT EXTRACT(YEAR FROM day), EXTRACT(WEEK FROM day)
    FROM UNNEST(
        GENERATE_DATE_ARRAY(DATE('2015-06-01'), CURRENT_DATE(), INTERVAL 1 WEEK)
    ) AS day
    
    0 讨论(0)
  • 2020-12-14 11:11

    all dates from 2015-06-01 till CURRENT_DATE()

    SELECT DATE(DATE_ADD(TIMESTAMP("2015-06-01"), pos - 1, "DAY")) AS DAY
    FROM (
         SELECT ROW_NUMBER() OVER() AS pos, *
         FROM (FLATTEN((
         SELECT SPLIT(RPAD('', 1 + DATEDIFF(TIMESTAMP(CURRENT_DATE()), TIMESTAMP("2015-06-01")), '.'),'') AS h
         FROM (SELECT NULL)),h
    )))
    

    all weeks between the two dates

    SELECT YEAR(DAY) AS y, WEEK(DAY) AS w
    FROM (
      SELECT DATE(DATE_ADD(TIMESTAMP("2015-06-01"), pos - 1, "DAY")) AS DAY
      FROM (
           SELECT ROW_NUMBER() OVER() AS pos, *
           FROM (FLATTEN((
           SELECT SPLIT(RPAD('', 1 + DATEDIFF(TIMESTAMP(CURRENT_DATE()), TIMESTAMP("2015-06-01")), '.'),'') AS h
           FROM (SELECT NULL)),h
      )))
    )
    GROUP BY y, w
    
    0 讨论(0)
提交回复
热议问题