日期:2014-05-18 浏览次数:20474 次
DROP TABLE tb0 CREATE TABLE tb0 ( id INT, pid INT, name VARCHAR(10) ) INSERT INTO tb0 SELECT 1, 0, 'AAA' UNION SELECT 2, 0, 'BBB' UNION SELECT 3, 1, 'CCC' UNION SELECT 4, 1, 'DDD' UNION SELECT 5, 2, 'EEE' UNION SELECT 6, 2, 'FFF' UNION SELECT 7, 2, 'GGG' SELECT Id,Pid,name FROM (SELECT CASE WHEN A.id = B.pid THEN B.id WHEN A.pid IS NULL THEN B.id ELSE A.pid END AS Id,CASE WHEN A.id IS NULL THEN B.id ELSE A.id END AS AId, B.pid,B.name FROM tb0 as A RIGHT OUTER JOIN tb0 as B ON A.id = B.pid) AS A ORDER BY AId,Id,pid Id Pid name 1 0 AAA 3 1 CCC 4 1 DDD 2 0 BBB 5 2 EEE 6 2 FFF 7 2 GGG
------解决方案--------------------
Declare @T Table (
id Int,
pid Int,
name varchar(20)
)
Insert Into @T
Select 1, 0, 'AAA'
Union Select 2, 0, 'BBB'
Union Select 3, 1, 'CCC'
Union Select 4, 1, 'DDD'
Union Select 5, 2, 'EEE'
Union Select 6, 2, 'FFF'
Union Select 7, 2, 'GGG'
Select * From @T
Order By case when Pid=0 then id else pid End,id