34,588
社区成员
发帖
与我相关
我的任务
分享
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([id] int,[name] nvarchar(23),[pid] int)
Insert #T
select 1,N'四川',0 union all
select 2,N'成都市',1 union all
select 3,N'高新区',2 union all
select 4,N'应龙县',2
Go
--测试数据结束
SELECT a.id AS fatherid,
a.name AS fathername,
b.id AS sonid,
b.name AS sonname
FROM #T a
JOIN #T b
ON a.id = b.pid
and a.pid=0
UNION ALL
SELECT a.id AS fatherid,
a.name AS fathername,
c.id AS sonid,
c.name AS sonname
FROM #T a
JOIN #T b
ON a.id = b.pid AND a.pid=0
JOIN #T c ON b.id=c.pid
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([id] int,[name] nvarchar(23),[pid] int)
Insert #T
select 1011,N'四川',0 union all
select 101111,N'成都市',1011 union all
select 10111101,N'高新区',101111 union all
select 10111101,N'应龙县',101111
Go
--测试数据结束
SELECT a.id AS fatherid,
a.name AS fathername,
b.id AS sonid,
b.name AS sonname
FROM #T a
JOIN #T b
ON a.id = LEFT(b.pid, 4)
AND a.pid = 0;