******请教sql语句如何写!! 急急急,在线等**********

hard_blue 2006-04-21 08:33:58
部门代码 级别 上级代码
01 1 null
0101 2 01
010101 3 0101
010102 3 0101
0102 2 01
010201 3 0102
010202 3 0102
02 1 null
0201 2 02
0202 2 02

用sql语句查询后,将结果显示成为
01 0101 010101
01 0101 010102
01 0102 010201
01 0102 010202
02 0201 null
02 0202 null

如何写啊?
...全文
111 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
冷箫轻笛 2006-04-21
  • 打赏
  • 举报
回复

select t1.部门代码 as 一级部门,t2.部门代码 as 二级部门,t3.部门代码 as 三级部门
from 表 t1 left join 表 t2 on t1.上级代码 = t2.部门代码 and t1.级别= 1 and t2.级别=2
left join 表 t3 on t2.上级代码 = t3.部门代码 and t2.级别= 2 and t3.级别=3



$扫地僧$ 2006-04-21
  • 打赏
  • 举报
回复
create table A
(
id varchar(10),
lev int,
p_id varchar(10)
)

insert A select '01',1, null
insert A select '0101',2,'01'
insert A select '010101',3,'0101'
insert A select '010102',3,'0101'
insert A select '0102',2,'01'
insert A select '010201',3,'0102'
insert A select '010202',3,'0102'
insert A select '02',1,null
insert A select '0201',2,'02'
insert A select '0202',2,'02'


select A1.id,Az.id2,Az.id3 from
(select id,p_id from A where lev=1) A1 left join
(select a2.id as id2,a3.id as id3,A2.p_id
from
(select id,p_id from A where lev=2) A2 left join (select id,p_id from A where lev=3) A3 on a2.id=a3.p_id) Az on A1.id =Az.p_id
冷箫轻笛 2006-04-21
  • 打赏
  • 举报
回复
解释一下结果跟原数据的关系吧
云中客 2006-04-21
  • 打赏
  • 举报
回复
select right(部门代码,2),上级代码,部门代码 from 表 order by 部门代码
hard_blue 2006-04-21
  • 打赏
  • 举报
回复
没人回答吗,自己顶

34,873

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧