2011-12-19 64 views
0

选择可能重复:
Sql question: Getting Parent rows followed by child rows如何订购我的递归在SQL

我 “按订单” 逐级递归结果需要。然后,我将使它像这样的结构:

Level | ID | Name  | Parent 
======================================= 
1  | 10 | **Rich** | 
2  | 11 | Sony  | **Rich** 
1  | 13 | Mary  | 
1  | 15 | **John** | 
2  | 12 | Lily  | **John** 

必须责令正因为如此,像树状结构:第一个元素 - 父母,然后孩子。

+2

您的表格有4个字段,有些记录只有3个值。如果你突出显示你的表并点击'{}',它将使它成为一个代码片段并被均匀分布(可读)。另外,你有超过2个关卡吗?你可以给出输入数据和所需输出格式/顺序的例子。 – MatBailie 2011-12-19 12:16:44

+0

看起来有人没有理解他们的功课... – 2011-12-19 12:31:09

回答

0

你试过

... ORDER BY CONCAT(IFNULL(parent,''),name) 
0

这里有一个递归,订货例如在T-SQL。

declare @table table(
    [level] int, 
    id int, 
    [name] nvarchar(32), 
    [parent] nvarchar(32) 
); 
insert into @table([level], id, [name], parent) values(1, 10, '**Rich**', null); 
insert into @table([level], id, [name], parent) values(2, 11, 'Sony', '**Rich**'); 
insert into @table([level], id, [name], parent) values(1, 13, 'Mary', null); 
insert into @table([level], id, [name], parent) values(1, 15, '**John**', null); 
insert into @table([level], id, [name], parent) values(2, 12, 'Lily', '**John**'); 

with rec ([level], id, [name], parent, seq) as (
    select 
      t.[level], 
      t.id, 
      t.[name], 
      t.[parent], 
      cast(t.[level] as varbinary(max)) as seq 
     from 
      @table as t 
     where 
      t.parent is null 
    union all select 
      t.[level], 
      t.id, 
      t.[name], 
      t.[parent], 
      r.seq + cast(t.[level] as varbinary(max)) as seq 
     from 
      rec as r 
      inner join @table as t 
       on t.parent = r.name 
) 
select 
     * 
    from 
     rec 
    order by 
     seq asc 
; 

要点这里(1)经由with递归和(2)串联电平数目的二进制表示成一个单一的序列指示符。