Bigquery-拆分功能

时间:2018-06-27 08:18:01

标签: python google-bigquery

INSERT INTO
    "Table Name" (
    CurrentMonthlastDate, 
    MonthLastDate,
    yearmonth)
SELECT DISTINCT 
               (SELECT 
                DATE_SUB(DATE_TRUNC(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), MONTH), INTERVAL 1 DAY) AS CurrentMonthlastDate),
                MonthLastDate, -- Get last day of month based on year.month
                yearmonth
                FROM
                "Table Name"

如果yearmonth的值为'2018.04',我该如何拆分并找出该月的最后一天? 是否可以拆分该值,并在插入记录时将月份的最后一天插入“ MonthLastDate”字段中。

3 个答案:

答案 0 :(得分:1)

#standardSQL
SELECT
  DATE_SUB(DATE_TRUNC(DATE_ADD(PARSE_DATE('%Y.%m',
          '2018.04'), INTERVAL 1 MONTH), MONTH), INTERVAL 1 DAY)

答案 1 :(得分:1)

(SELECT DATE_SUB(DATE_TRUNC(DATE_ADD(DATE(CAST(REGEXP_EXTRACT(CAST(yearmonth AS STRING),'(。)...')AS AS INT64), CAST(REGEXP_EXTRACT(CAST(yearmonth AS STRING),'.....(。)')AS INT64),01),INTERVAL 1 MONTH),MONTH),INTERVAL 1 DAY)AS MonthLastDate

我自己弄的。谢谢!

答案 2 :(得分:1)

以下是用于BigQuery标准SQL

#standardSQL
SELECT 
  DATE_SUB(
    DATE_ADD(PARSE_DATE('%Y.%m', yearmonth), INTERVAL 1 MONTH), 
    INTERVAL 1 DAY
  ) MonthLastDate

您可以使用下面的虚拟数据进行测试/播放

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '2018.04' AS yearmonth  UNION ALL
  SELECT '2018.02'
)
SELECT 
  yearmonth, 
  DATE_SUB(
    DATE_ADD(PARSE_DATE('%Y.%m', yearmonth), INTERVAL 1 MONTH), 
    INTERVAL 1 DAY
  ) MonthLastDate
FROM `project.dataset.table`  

结果是

Row yearmonth   MonthLastDate    
1   2018.04     2018-04-30   
2   2018.02     2018-02-28