bigquery选择logtime低于其他表logtime的min(值)的行

r6vfmomb  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(269)

假设我有以下两张表:
表1:

ID     log_time 
1      2013-10-12
1      2014-11-15
2      2013-12-21
2      2016-12-21
3      2015-09-21
3      2018-03-21

表2:

ID     log_time 
1      2011-10-12
1      2012-11-15
2      2012-12-21
2      2017-12-21
3      2014-09-21
3      2019-03-21

我想为每个id获取表2中低于表1的min(logu time)的行。结果如下:

ID     log_time 
1      2011-10-12
1      2012-11-15
2      2012-12-21
3      2015-09-21
68de4m5k

68de4m5k1#

这是 join 和聚合:

select t2.*
from table2 t2 join
     (select t1.id, min(t1.log_time) as min_log_time
      from table1 t1
      group by t1.id
     ) t1
     on t2.id = t.id and t2.timestamp < t1.timestamp;

也可以将其表示为相关子查询:

select t2.*
from table2 t2
where t2.log_time < (select min(t1.log_time) from t1 where t1.id = t2.id);

请注意,这两个公式都不会返回缺少的id行 table1 (这和你的问题很一致)。

相关问题