首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

pid为 n 的行 跟在 id 为 n 的行后面,如何实现

2014-05-31 
pid为 n 的行 跟在 id 为 n 的行后面,怎么实现?数据库如下:idpidname10AAA20BBB31CCC41DDD52EEE62FFF72GGG

pid为 n 的行 跟在 id 为 n 的行后面,怎么实现?
数据库如下:
idpidname
10AAA
20BBB
31CCC
41DDD
52EEE
62FFF
72GGG

想要得到的结果:
idpidname
10AAA
31CCC
41DDD
20BBB
52EEE
62FFF
72GGG

就是说,pid为 n 的行 跟在 id 为 n 的行后面,
期待高手出现

[解决办法]
select a,b,c from (select d.*,case when b=0 then a else b end as d from (
select 1 as A, 0 as b,'AAA' as C union all 
select 2 as A, 0 as b,'BBB' as C union all 
select 3 as A, 1 as b,'CCC' as C union all 
select 4 as A, 1 as b,'DDD' as C union all 
select 5 as A, 2 as b,'EEE' as C union all 
select 6 as A, 2 as b,'FFF' as C union all 
select 7 as A, 2 as b,'GGG' as C )d)E order by d,a
[解决办法]

SQL code
DROP TABLE tb0CREATE TABLE tb0(    id INT,    pid INT,    name VARCHAR(10))INSERT INTO tb0SELECT 1, 0, 'AAA' UNIONSELECT 2, 0, 'BBB' UNIONSELECT 3, 1, 'CCC' UNIONSELECT 4, 1, 'DDD' UNIONSELECT 5, 2, 'EEE' UNIONSELECT 6, 2, 'FFF' UNIONSELECT 7, 2, 'GGG'SELECT Id,Pid,nameFROM (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.nameFROM tb0 as A RIGHT OUTER JOIN tb0 as B ON A.id = B.pid) AS AORDER BY AId,Id,pidId    Pid    name1    0    AAA3    1    CCC4    1    DDD2    0    BBB5    2    EEE6    2    FFF7    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
SQL code
 

热点排行