【问题标题】:How to convert separate year and month column into a single date and get the difference between two dates in terms of months/days如何将单独的年份和月份列转换为单个日期并获取两个日期之间的月/日差异
【发布时间】:2019-12-09 09:17:25
【问题描述】:

在 google bigquery 中加入两个表后,我最终得到了一个表,该表在四个单独的列中包含两组年份和月份。前两年和月份列应构成一个日期,第二对构成另一个日期。我需要将这两组年份和月份中的每一个转换为两个单独的日期,然后以月或日的形式获得这两个日期之间的差异。

  Example of the table is provided below: 

       year    month    year    month
    0  2013     12      2014      2
    1  2014     5       2014      9
    2  2015     6       2015      8

如果有人可以帮助在 bigquery 中编写此代码,那将非常有帮助。 提前致谢。

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:
    #standardSQL
    WITH `project.dataset.table` AS (
      SELECT 2013 year1, 12 month1, 2014 year2, 2 month2 UNION ALL
      SELECT 2014, 5, 2014, 9 UNION ALL
      SELECT 2015, 6, 2015, 8 
    )
    SELECT 
      DATE(year1, month1, 1) date1, 
      DATE(year2, month2, 1) date2,
      DATE_DIFF(DATE(year2, month2, 1), DATE(year1, month1, 1), DAY) diff_in_days
    FROM `project.dataset.table`   
    

    结果

    Row date1       date2       diff_in_days     
    1   2013-12-01  2014-02-01  62   
    2   2014-05-01  2014-09-01  123  
    3   2015-06-01  2015-08-01  61   
    

    【讨论】:

      【解决方案2】:

      要获得月份的差异,您无需转换为日期。只需使用算术:

      select (year1 * 12 + month1) - (year2 * 12 + month2)
      

      【讨论】:

        【解决方案3】:

        因此,您可以使用 DATE(YEAR,MONTH,DAY) 函数两次传递两列上的数据并将 1 作为日期传递,因为这无关紧要,然后使用 DATE_DIFF(date_expression, date_expression , date_part) 传递您从这些函数获得的日期以及您想要作为返回的日期部分,它接受: DAY、WEEK、ISOWEEK、MONTH、QUARTER、YEAR 和 ISOYEAR。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-12-24
          • 2014-04-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多