如何对值(具有2个元素的行)进行排序,其中第二列是前一行/第一列的链接,其中值是数字但不能按正常数值顺序/计算值排序,例如:
1 - 0 no previous row
3 - 1 1 in second colum refers to 1 in previous row in first column
4 - 3 3 in second colum refers to 3 in previous row in first column
2 - 4 ...
9 - 2
7 - 9
5 - 7
6 - 5
8 - 6
排序结果应为:1 - 3 - 4 - 2 - 9 - 7 - 5 - 6 - 8
棘手的部分是未知的序列,所以case,decode,if,...不能被包含,因为值是未知的(唯一知道的是第二列中的第一行0) )
有人已经解决了这样的排序顺序吗?
答案 0 :(得分:0)
create table #t (
valor int null
, valor2 int null
, linha int not null identity
)
insert into #t (valor) values (1)
insert into #t (valor) values (3)
insert into #t (valor) values (4)
insert into #t (valor) values (2)
insert into #t (valor) values (9)
insert into #t (valor) values (7)
insert into #t (valor) values (5)
insert into #t (valor) values (6)
insert into #t (valor) values (8)
update #t set #t.valor2 = isnull(t2.valor, 0)
from (
select valor, linha +1 as linha
from #t
) t2
where #t.linha = t2.linha
select valor, valor2, linha from #t order by linha
select valor, isnull(valor2, 0) as valor2 from #t order by 2
drop table #t
结果如下: