SELECT * FROM TB ORDER BY CASE WHEN 附属编号<>'' THEN 附属编号 ELSE 编号 END,编号这样应该可以
解决方案 »
- 数据库重新安装问题Setup has detected that unInstallShield is in use
- 求一更新语句
- 非一般的问题
- 这个不会
- 在触发器中如何得到当前执行的SQL
- 因为数据类型不同,所以UPDATE后出现问题。 求解
- 在日文版WIN2000(PROFESSIANAL)下能否安装SQL SERVER2000,是否有字体不兼容或显示不出的问题?
- 我使用的是sqlserver2000,我怎么清除日志文件,现在我的数据库的日志特别大,如何压缩
- sql里。如何取一个datetime字段的小时的值。。年,月,日都能取,怎么小时不能取啊。惨
- 求一个SQL查询语句
- 大神进来,求一条查询语句,急!!!
- sql多对多分配数据的存储过程
-- 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
*/