我在ORACLE中有2个经纬度和经度的表,我正在计算这两个位置之间的距离,并根据它计算Adherence报告。我想选择干扰VISITOR_ID行,优先选择具有坚持性的访客为' N'。以下是我正在使用的查询,我还附加了查询的示例输出。
SELECT DISTINCT rv.VISITOR_ID as VISITOR_ID, rv.VISIT_ENT_NAME as Location_Name,
ACOS(SIN(RADIANS(rg.Latitude)) * SIN(RADIANS(rv.Latitude))
+ COS(RADIANS(rg.Latitude)) * COS(RADIANS(rv.Latitude))
* COS(RADIANS(rg.Longitude) - RADIANS(rv.Longitude))
) * 6371 AS DISTANCE,
(CASE WHEN ACOS(SIN(RADIANS(rg.Latitude)) * SIN(RADIANS(rv.Latitude))
+ COS(RADIANS(rg.Latitude)) * COS(RADIANS(rv.Latitude))
* COS(RADIANS(rg.Longitude) - RADIANS(rv.Longitude))
) * 6371 < 200 THEN 'Y' ELSE 'N' END) AS Adherence
From RANDOM_VISIT rv
LEFT JOIN GEOTAG rg ON rv.VISITOR_ID = rg.CODE;
查询结果:
预期结果应该是选择不同的visitor_id但是在选择distint时要优先考虑遵守=&#39; N&#39;:
答案 0 :(得分:2)
所有在一个(附加)查询中 - 使用Aleksej的样本数据:
with yourQueryResult (visitor_id, location_name, distance, adherence) as
(
select 5200, 'Mobi Shop', 0.4, 'N' from dual union all
select 7550, 'Sk cafe', 0.7, 'N' from dual union all
select 7550, 'DL General', 0.7, 'N' from dual union all
select 5200, 'Success Mobo', 0.1, 'Y' from dual union all
select 7550, 'Mack Agency', 0.9, 'N' from dual
)
select visitor_id,
min(location_name) keep (dense_rank first order by adherence, distance)
as location_name,
min(distance) keep (dense_rank first order by adherence) as distance,
min(adherence) as adherence
from yourQueryResult
group by visitor_id;
答案 1 :(得分:1)
尝试简化,假设您的查询提供了结果,这可能是获得所需内容的一种方式。
with yourQuery (visitor_id, location_name, distance, adherence) as
(
select 5200, 'Mobi Shop', 0.4, 'N' from dual union all
select 7550, 'Sk cafe', 0.7, 'N' from dual union all
select 7550, 'DL General', 0.7, 'N' from dual union all
select 5200, 'Success Mobo', 0.1, 'Y' from dual union all
select 7550, 'Mack Agency', 0.9, 'N' from dual
)
select visitor_id, location_name, distance, adherence
from (
select q.*, row_number() over (partition by visitor_id order by adherence) as RN
from yourQuery q
)
where RN = 1
如果有许多行具有相同的visitor_id
和adherence = 'N'
,则没有逻辑可以决定要提取哪一行;如果您需要逻辑,则可以相应地编辑ORDER BY
部分。