declare @t table(a varchar(2),b varchar(2)) insert @t select 'A' , 'B' union all select 'B' , 'C' union all select 'C' , 'D' union all select 'D' , 'E'select a,b=(select top 1 b from @t order by a desc) from @t a b ---- ---- A E B E C E D E(所影响的行数为 4 行)
楼上几位的都正确的。LZ可以参考下。不过LZ太不厚道了,尽然是O分贴!哈哈
呵呵~~不好意思,小弟刚来,没分 更正一下,原说明 现有表T(old,new),如下记录 A B B C C D D E F G G H I J 使用一个什么方法可得到如下结果 A E B E C E D E F H G H I J
declare @a varchar(..) select @a=max(new) from T select old,@a from T
是SQL Server吗?如果是,我写一个简单的函数给你吧CREATE function dbo.GetLast (@a nvarchar(50)) returns nvarchar(50) AS begin while (select count(old) from T where old like @a)>0 begin select @a=new from Twhere old like @a end RETURN @a end建立了这个函数后,就容易多了 select old,GetLast(old) new from T
有一点错误,while里面的那个查询的T和where 写到一起了,得分开,另外最后那个查询最好这样写 select old,dbo.GetLast(old) new from T
declare @t table(col1 varchar(10),col2 varchar(10)) insert into @t select 'A','B' union all select 'B','C' union all select 'C','D' union all select 'D','E' union all select 'F','M' union all select 'H','J' union all select 'J','I'select col1, case when (select count(*) from @t where t.col2 = col1) > 0 then '1' else col2 end col2 into #temp1 from @t t select col1, case when col2 = '1' then (select top 1 col2 from #temp1 where col2 <> '1' and t.col1 < col1) else col2 end col2 from #temp1 t测试下!!!
insert @t select 'A' , 'B'
union all select 'B' , 'C'
union all select 'C' , 'D'
union all select 'D' , 'E'select a,b=(select top 1 b from @t order by a desc) from @t
a b
---- ----
A E
B E
C E
D E(所影响的行数为 4 行)
更正一下,原说明
现有表T(old,new),如下记录
A B
B C
C D
D E
F G
G H
I J
使用一个什么方法可得到如下结果
A E
B E
C E
D E
F H
G H
I J
select @a=max(new) from T
select old,@a from T
begin
while (select count(old) from T where old like @a)>0
begin
select @a=new from Twhere old like @a
end
RETURN @a
end建立了这个函数后,就容易多了
select old,GetLast(old) new from T
insert into @t select 'A','B'
union all select 'B','C'
union all select 'C','D'
union all select 'D','E'
union all select 'F','M'
union all select 'H','J'
union all select 'J','I'select col1,
case when (select count(*) from @t where t.col2 = col1) > 0 then '1'
else col2 end col2 into #temp1
from @t t
select col1,
case when col2 = '1' then (select top 1 col2 from #temp1 where col2 <> '1' and t.col1 < col1)
else col2 end col2
from #temp1 t测试下!!!