获得最大值

时间:2016-10-19 05:51:51

标签: sql oracle max

我试图检索距离一组XY坐标最远的所有目击事件,我能够检索先前查询中给出最大距离的第一行。但是,如果在同一坐标处发生目击,它无法处理多个最大值。

我尝试了两种不同的方法来尝试获得最大值:

WITH params as (
          SELECT -28 as lat, 151 as lon
          FROM dual
         )
    SELECT sighting_id, sqrt(power(lat - latitude, 2) + power(lon - longitude,  2)
    ) 
    AS distance

    FROM sightings CROSS JOIN params

    WHERE sqrt(power(lat - latitude, 2) + power(lon - longitude, 2)) = 
     (select * from (select sighting_id, 
      sqrt(power(lat - latitude, 2) + power(lon - longitude, 2)) 

    FROM sightings CROSS JOIN params

    ORDER BY sqrt(power(lat - latitude, 2) + power(lon - longitude, 2)) desc )

    WHERE rownum <= 1);

WITH params as (
              SELECT -28 as lat, 151 as lon
              FROM dual
             )
        SELECT sighting_id, sqrt(power(lat - latitude, 2) + power(lon - longitude,  2)
        ) 
        AS distance

        FROM sightings CROSS JOIN params

        WHERE sqrt(power(lat - latitude, 2) + power(lon - longitude, 2)) = 
         (SELECT MAX(sqrt(power(lat - latitude, 2) + power(lon - longitude, 2))) 

        FROM sightings CROSS JOIN params);

第一种方式错误说太多的值,第二种方式说我不能使用MAX()超过欧几里德距离。我该如何克服这个问题?

2 个答案:

答案 0 :(得分:0)

据我了解你想要占用最大距离。你可以尝试下面的一个,让我知道它是否有效?

WITH params AS      (SELECT -28 AS lat,151 AS lon         从双方) 选择sighting_id,距离   FROM(SELECT sighting_id,                SQRT(POWER(纬度 - 纬度,2)+ POWER(经度 - 经度,2)                     )AS距离,                MAX(SQRT(POWER(纬度 - 纬度,2)                           + POWER(经度 - 经度,2)                          )                    )OVER(PARINGTION by sighting_id)AS max_distance           从目击CROSS JOIN params                )dat  WHERE dat.distance = max_distance

此致,Niraj

答案 1 :(得分:0)

在第一个查询中,你在where子句中犯了两个错误。您尝试比较read() returns -1ServerSocket返回多个值。接下来,你从零开始尝试SQRT(...) = select * ...。你应该指出它。你可以把它重写为

Select *...

select sighting_id, 
      sqrt(power(lat - latitude, 2) + power(lon - longitude, 2)

或用分析函数重写它

WITH params as (
      SELECT -28 as lat, 151 as lon
      FROM dual
     )
SELECT sighting_id, 
       sqrt(power(lat - latitude, 2) + power(lon - longitude,  2))  AS distance
FROM sightings 
CROSS JOIN params
WHERE sqrt(power(lat - latitude, 2) + power(lon - longitude, 2)) = 
 (select max_value 
   from ( select sqrt(power(lat - latitude, 2) + power(lon - longitude, 2) as max_value  
         FROM sightings CROSS JOIN param
         order by sqrt(power(lat - latitude, 2) + power(lon - longitude, 2) desc)
  where rownum <=1)  
ORDER BY sqrt(power(lat - latitude, 2) + power(lon - longitude, 2)) desc ));