簡體   English   中英

where 語句過濾特定日期時間格式 sql bigquery

[英]where statement to filter specific datetime format sql bigquery

我有一個查詢,逐行輸出數據,對於每條記錄,我從last_modified_date列中獲取一個值,該值是該列中的最新日期,但不遲於date列的值。 我將新值保存在custom_last_modified_date列中。 我的數據如下所示:

id           date           last_modified_date
A           03/01/22          2022-03-02 22:44
A           03/01/22          2022-02-01 05:14
A           03/01/01          2022-02-28 07:49
B           03/02/22          2022-03-20 07:49
B           03/02/22          2022-03-01 04:46
B           03/02/01          2022-02-28 09:24

輸出是:

id           date        custom_last_modified_date
A           03/01/22          02/28/22
A           03/01/22          02/28/22
A           03/01/01          02/28/22
B           03/02/22          03/01/22
B           03/02/22          03/01/22
B           03/02/01          03/01/22

這是代碼:

SELECT 
id, 
date,
MAX(
        IF(
            date(
                string(
                    TIMESTAMP(
                        DATETIME(
                            parse_datetime('%Y-%m-%d %H:%M', last_modified_date)
                        ),
                        'America/New_York'
                    )
                )
            ) <= date,
            date(
                string(
                    TIMESTAMP(
                        DATETIME(
                            parse_datetime('%Y-%m-%d %H:%M', last_modified_date)
                        ),
                        'America/New_York'
                    )
                )
            ),
            null
        )
    ) OVER (PARTITION BY date, id) as custom_last_modified_date
FROM `my_table`

樣本上一切正常,但由於數據不是很干凈,有時last_modified_date中的值看起來像這樣: "2021-0-3 05:50" ,然后錯誤消息是: Failed to parse有沒有辦法過濾掉正確的where 子句中的日期格式或以其他方式排除同一查詢中的錯誤值? 謝謝你。

您可以使用SAFE前綴來忽略解析器錯誤,然后您可以過濾null行:

-- Returns null if last_modified_date not match the expected pattern
SAFE.parse_datetime('%Y-%m-%d %H:%M', last_modified_date)

從文檔:

如果您使用 SAFE 開始一個功能。 前綴,它將返回 NULL 而不是錯誤。

[...]

BigQuery 支持使用 SAFE。 大多數可能引發錯誤的標量函數的前綴,包括 STRING 函數、數學函數、DATE 函數、DATETIME 函數、TIMESTAMP 函數和 JSON 函數。

更多信息: https ://cloud.google.com/bigquery/docs/reference/standard-sql/functions-reference#safe_prefix

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM