简体   繁体   English

Google BigQuery 时间戳比较

[英]Google BigQuery timestamp comparison

there is a table "tbl1", having columns "name, surname, log_date".有一个表“tbl1”,包含列“name、surname、log_date”。 "log_date" is timestamp type. “log_date”是timestamp类型。

How can I retrieve the records logged yesterday?如何找回昨天的记录?

I am struggling with timestamp variable, I did something like:我在timestamp变量上苦苦挣扎,我做了类似的事情:

declare yesterday timestamp
set (yesterday) = select TIMESTAMP_ADD(EXTRACT(Date FROM CURRENT_TIMESTAMP()), interval -1 day);

Above fails, so I am not able to use it later in my script:上面失败了,所以我以后不能在我的脚本中使用它:

SELECT distinct 
    name
FROM 
    `xxx.tbl1`
WHERE 
    log_date > yesterday

Also I tried:我也试过:

SELECT 
    distinct name
FROM 
    `xxx.tbl1`
WHERE 
  log_date > TIMESTAMP_ADD(EXTRACT(Date FROM CURRENT_TIMESTAMP()), interval -1 day)

or或者

SELECT 
    distinct name
FROM 
    `xxx.tbl1`
WHERE 
  log_date > Select TIMESTAMP_ADD(EXTRACT(Date FROM CURRENT_TIMESTAMP()), interval -1 day)

or或者

WITH vars AS (
  SELECT EXTRACT(Select TIMESTAMP_ADD(EXTRACT(Date FROM CURRENT_TIMESTAMP()), interval -1 day) AS CustomDay
)
SELECT distinct 
    distinct name
FROM 
    `xxx.tbl1`, vars
WHERE 
    log_date > CustomDay

No luck.没有运气。

Is there any other way, how to parse yesterday's date and use it in the select statement later on?有没有其他方法,如何解析昨天的日期并在稍后的 select 语句中使用它?

Without knowing the error you are getting, it seems that the problem is that you are trying to compare a timestamp (the log_date ) with datetime (the extracted DATE ).在不知道您收到的错误的情况下,问题似乎是您正在尝试将timestamplog_date )与datetime时间(提取的DATE )进行比较。 This should work:这应该有效:

SELECT 
    distinct name
FROM 
    `xxx.tbl1`
WHERE 
  DATE(log_date) = DATE_ADD(EXTRACT(DATE FROM CURRENT_TIMESTAMP()), INTERVAL -1 DAY)

Important: Use = for comparison to get the logs from yesterday only, > will get you the logs from today onwards.重要提示:使用=进行比较以仅获取昨天的日志, >将获取从今天开始的日志。

One little thing: I would use DATE_SUB to subtract days instead of DATE_ADD with -1 (for readability), but kept it like that because of your example code.一件小事:我会使用DATE_SUB减去天数而不是DATE_ADD减去-1 (为了可读性),但由于您的示例代码而保持这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM