22,299
社区成员




----------------------------------------------------------------
-- Author :DBA_HuangZJ(發糞塗牆)
-- Date :2014-11-11 13:18:31
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3153.0 (X64)
-- Jul 22 2014 15:26:36
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([编号] int,[名称] varchar(2),[附属编号] int)
insert [huang]
select 1,'AA',null union all
select 2,'BB',null union all
select 3,'CC',null union all
select 4,'DD',null union all
select 5,'EE',1 union all
select 6,'FF',3 union all
select 7,'GG',1 union all
select 8,'HH',4 union all
select 9,'JJ',1
--------------开始查询--------------------------
;with cte as (
select * ,编号 as [level]
from [huang]
where 附属编号 is null
),
cte1 as
(
select * from cte where [level]=0
union all
select a.*,b.[level]-- as [level]
from huang a inner join cte b on a.附属编号=b.编号
)
select 编号,名称,附属编号
from (
select * from cte1
union all
select * from cte)a
order by [level],编号
----------------结果----------------------------
/*
编号 名称 附属编号
----------- ---- -----------
1 AA NULL
5 EE 1
7 GG 1
9 JJ 1
2 BB NULL
3 CC NULL
6 FF 3
4 DD NULL
8 HH 4
*/
SELECT * FROM TB ORDER BY CASE WHEN 附属编号<>'' THEN 附属编号 ELSE 编号 END,编号
这样应该可以