在数据库表中,基于一个列值获取记录,而该值基于其他两列

时间:2018-10-10 08:42:29

标签: sql oracle

我有下表:

 username | timestamp   | distance_location1 | distance_location2
  jack     1532101253000   22.2541(km)           152.652(km)

我正在使用的查询是

 select * 
 from   table 
 where  timestamp >= (select min(distance_location1) from table 
   AND  timestamp <= (select min(distance_location2) from table

我想获取基于timestamp列的记录。

时间戳的起始值是最小distance_location1。

时间戳的结束值是最小distance_location2

上面的查询不起作用,因为它给出了0条记录

2 个答案:

答案 0 :(得分:1)

如果distance_location1是数据类型是时间戳,则下面的查询将起作用 您将括号放在错误位置的位置

select * 
     from   table 
     where  timestamp >=
      ( select min(distance_location1 from table )
       AND  timestamp <= (select min(distance_location2 from table)

但是,如果distance_location1和distance_location2不是数据类型时间戳

select * from table
where timestamp>= (select min(timestamp)  from table t where t.distance_location1=(select min(distance_location1) from table)
) and

 timestamp<=( select min(timestamp)  from table t where t.distance_location2=(select min(distance_location2) from table))

答案 1 :(得分:0)

您需要比较时间戳,而不是距离。在Oracle中,您可以使用keep和分析函数:

select t.* 
from (select t.*,
             min(timestamp) keep (dense_rank first over order by distance_location1) as distance_location1_timestamp,
             min(timestamp) keep (dense_rank first over order by distance_location2) as distance_location2_timestamp
      from table t
     ) t
where timestamp >= distance_location1_timestamp and
      timestamp <= distance_location2_timestamp;