2017-01-05 4 views
0

2番目の列が前の行/最初の列へのリンクである値を並べ替える方法(2要素の行)は、値は数値ですが、通常の数値の並べ替えはできません。 :SQL独自の並べ替え順

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 - 3 - 2から7 - 9 - 6 - - 5、8

トリッキーな部分は、未知の配列であり、そう場合、デコード、もし。 ..は値が不明であるため含まれません(2番目の列では最初の行が0であることがわかります)

誰かがすでにそのような並べ替えの問題を解決していますか?

+0

タグあなたが求めている何 – GurV

+1

を使用しているデータベースは、ツリーの問題として考えることができ、かつツリー固有のSQLは、ベンダーによって異なります。 MySQLの場合は、 http://stackoverflow.com/questions/27579716/get-root-path-of-a-tree-with-pure-mysqlさらに、同様の質問に対する回答から、以下のような有用な点が判明しています。http://mikehillyer.com/ articles/manage-hierarchical-data-in-mysql / – alttag

答えて

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 

結果のようなものです:

First result ordered by the numbers input, and the second is the final result

関連する問題