2015-11-19 41 views
0

我正在尝试为数据集中的每个走廊查找最大的milage走廊段数。我用这个非常类似的查询找出最小milage,或增加方向走廊第一段和这个工作得很好:查找数据集中每个走廊的最大里程数参考

select distinct t.corridor_code_rb,t.frfpost,t.trfpost 
from SEC_SEGMENTS t 
where t.dir = 'I' and t.lane = 1 
and t.frfpost = (select min(s.frfpost) from SEC_SEGMENTS s) 
order by 1,2 

然而,当我尝试使用类似的查询发现最大的问题出现(最后一段中增加方向)用下面的查询走廊长度:

select distinct t.corridor_code_rb,t.frfpost,t.trfpost 
from SEC_SEGMENTS t 
where t.dir = 'I' and t.lane = 1 
and t.trfpost = (select max(s.trfpost) from SEC_SEGMENTS s) 
group by t.corridor_code_rb,t.frfpost,t.trfpost 

当我运行此查询是只输出第一走廊最高milage段会发生什么,然后停止。而最低的查询,它返回每个走廊的输出,这是我想要的。 frfpost是每个部分的开始英里,trfpost是结尾的milage。所以frfpost是'来自参考帖子',而trfpost是'参考帖子'。每条走廊通常在与其他走廊之间的路口之间分成长度介于5至40英里之间的路段。我试图找到每个走廊的最后部分,因此问题出在哪里。

+0

什么是你的DBMS?它支持RANK吗? – dnoeth

+0

我使用pl-sql开发人员。我不知道排名 –

回答

1

您还需要group by corridor_code_rb以获得每个corridor_code_rb该列的max值。然后join它到主表。

select t.corridor_code_rb,t.frfpost,t.trfpost 
from SEC_SEGMENTS t 
join (select corridor_code_rb, max(s.trfpost) as trfpost from SEC_SEGMENTS 
     group by corridor_code_rb) s 
on t.trfpost = s.trfpost 
where t.dir = 'I' and t.lane = 1 
1

基于您的评论你似乎使用Oracle,它支持解析函数:

Select corridor_code_rb, frfpost, tropfst 
from 
(
    select corridor_code_rb, frfpost, trfpost, 
     ROW_NUMBER()      -- rank the rows 
     OVER (PARTITION BY corridor_code_rb -- for each corridor 
      ORDER BY trfpost DESC) AS rn -- by descending direction 
    from SEC_SEGMENTS t 
    where t.dir = 'I' and t.lane = 1 
) dt 
WHERE rn = 1 -- filter the last row