我只想要更改县名的行

时间:2014-11-14 16:31:51

标签: sql plsql

我试图找到沿着公路路线发生县城变化的地点的路线,里程碑和县名。我是SQL的新手,所以我使用的查询非常简单:

select NRLG_ROUTE,NRLG_MILEPOINT,NRLG_COUNTY
from TIS.TIS_NEW_ROADLOG t
order by 1

所以我想要做的就是找到NRLG_COUNTY只出现在NRLG_ROUTES从一个县变为另一个县的行。我只是不希望每个县内或通过每个县的数据行,只是在边界。

2 个答案:

答案 0 :(得分:0)

如果我理解正确,你想知道" next"县不同于当前的"县,基于milepoint。这建议使用lead()

select rl.*
from (select rl.nrlg_route, rl.nrlg_milepoint, rl.nrlg_county,
             lead(rl.nrlg_county) over (partition by rl.nrlg_route
                                        order by rl.nrlg_milepoint) as next_county
      from tis.tis_new_roadlog rl
     ) rl
where county <> next_country;

答案 1 :(得分:0)

在SQL中,您只将条件应用于一行(每行),而不是连续行。也就是说,除非您将分析函数与over一起使用。

因此,您需要将表连接到自己,并按所需顺序移动一行。这是一个例子(在SQLite上测试):

# prepare some data
create table route(ordinal int not null primary key, road varchar(10));
insert into route values(1, "foo");
insert into route values (2, "foo");
insert into route values (3, "bar");
insert into route values (4, "bar");
insert into route values (5, "baz");

# the query
select 
  r1.ordinal, r1.road as "from", r2.road as "to"
from 
  route r1, route r2  # same table under different aliases
where 
  r1.ordinal = r2.ordinal - 1 and # r2 record goes right after r1
  r1.road != r2.road # the road has changed
;

预计会给出:

    from  to
2 | foo | bar
4 | bar | baz

如果您的序数(NRLG_ROUTE)有洞,那将会有点棘手。