在Google BigQuery中根据DateTime范围查找记录

时间:2016-08-12 18:44:26

标签: google-bigquery

我试图根据tb2中的DateTime范围为tb1中的每个id选择纬度和经度。

在tb2中,对于每个id,有4个DateTime。我需要从tb2获得DateTime范围。

例如,对于id = 162,tb2将类似于

id        DateTime
162     2016-08-12 00:02:13 UTC
162     2016-08-12 00:04:55 UTC
162     2016-08-12 00:24:03 UTC
162     2016-08-12 00:24:30 UTC

对于tb2中的这个id,我应该从tb1获得纬度和经度,其中c.DateTime应该在'2016-08-12 00:02:13 UTC'和'2016-08-12 00:24:30之间世界标准时间'。不确定如何为每个id选择第一行和最后一行并在其上应用范围函数。任何帮助将不胜感激。

SELECT
*
FROM (
 SELECT
 c.HardwareId AS HardwareId,
 d.DateTime AS DateTime,
 c.Latitude AS Latitude,
 c.Longitude AS Longitude
 FROM (
  SELECT
   *
  FROM
   [db1.tb2]) AS d
  INNER JOIN (
    SELECT
     Latitude,
     Longitude,
     Id,
     DateTime
    FROM TABLE_DATE_RANGE([db1.tb1],TIMESTAMP(CURRENT_TIMESTAMP()),TIMESTAMP(CURRENT_TIMESTAMP())) AS c
 ON
 d.Id = c.Id
 AND c.DateTime = d.DateTime)

1 个答案:

答案 0 :(得分:1)

由于您只需要Max(DateTime)和Min(DateTime),请尝试使用

SELECT c.HardwareId AS HardwareId, c.DateTime AS DateTime,
       c.Latitude AS Latitude, c.Longitude AS Longitude
FROM
(
  SELECT id, MAX(DateTime) AS MaxDatetime, MIN(DateTime) as MinDateTime
  FROM [db1.tb2]
  GROUP BY id
) AS d
JOIN
[db1.tb1] AS c
ON c.Id = d.Id
WHERE c.DateTime >= d.MinDateTime and c.DateTime <= d.MaxDateTime