Sql Server同表内的级联排序

时间:2021-06-27 13:32:00

Sql Server同表内的级联排序(即同父级别的子节点自行按1~N排序),2005版本已经自带了ROW_NUMBER() OVER子句,可以很方便地实现效果。但是2000版本不支持这种做法,不过也可以采取特殊做法

 

--slq2005
select rd.id,r.id ruleId,ROW_NUMBER() OVER(
    PARTITION BY r.id
    ORDER BY rd.id) ord,
r.name+'--'+rd.name rule_name,
score from rules_detail rd left join rules r
on rd.rules_id=r.id

 

--slq2000

select rd.id,r.id ruleId,

(select count(*) from rules_detail rde left join rules ru
on rde.rules_id=ru.id where ru.id=r.id and (rd.id>rde.id or rd.id=rde.id)) ord,

r.name+'--'+rd.name rule_name,
score from rules_detail rd left join rules r
on rd.rules_id=r.id