连接表时的子句条件

时间:2016-10-06 16:09:55

标签: sql google-bigquery

我想加入两个表“Table1”和“Table2”。对于Table1中的每个Id,我必须获取StartTime和StopTime,并参考Table2,其DateTime在表1的StartTime和StopTime之间,然后从表2中检索相应的Point 1和Point 2.我尝试连接这两个表,在on子句中,我检查了Table1.StartTime> = Table2.DateTime和Table1.StopTime< = Table2.DateTime。但Google大查询不支持> = in in子句。只是想知道是否有任何补充。任何帮助将不胜感激。

表1:

Id    StartTime                 StopTime    

1    2016-10-05 12:44:21 UTC    2016-10-05 12:59:31 UTC

表2:

Id  DateTime                   Point1       Point2

1   2016-10-05 12:44:21 UTC     52.9        53.2
2   2016-10-05 12:44:24 UTC     33.1        90.1
3   2016-10-05 12:50:47 UTC     52.3        90.8
4   2016-10-05 12:53:23 UTC     52.3        -111.11

结果表:

Id    StartTime                 StopTime                Point1      Point2

1    2016-10-05 12:44:21 UTC    2016-10-05 12:59:31 UTC   52.9      53.2
2    2016-10-05 12:44:21 UTC    2016-10-05 12:59:31 UTC   33.1      90.1
3    2016-10-05 12:44:21 UTC    2016-10-05 12:59:31 UTC   52.3      90.8
4    2016-10-05 12:44:21 UTC    2016-10-05 12:59:31 UTC   52.3     -111.11

1 个答案:

答案 0 :(得分:2)

对于BigQuery Standard SQL(请参阅Enabling Standard SQL

SELECT Table1.Id, StartTime, StopTime, Point1, Point2
FROM Table1 join Table2
ON Table1.StartTime <= Table2.DateTime 
AND Table1.StopTime >= Table2.DateTime

或者您可以在ON子句

中使用以下内容
ON Table2.DateTime BETWEEN Table1.StartTime AND Table1.StopTime