求一复杂查询语句~~~~~~~~急~~~~~~~~~~

ziyulin0311 2007-05-18 09:33:17
表1
user(员工) dept(部门)
张三 it部
李四 人事科
小王 第一产品科

注:人事科属于行政部

表2
dept_name(子部门) dept_parent(主部门)
it部 it中心
人事科 行政部
行政部 行政中心
第一产品科 第一产品软件部
第一产品软件部 第一产品部
第一产品部 研发中心


问题是 sql语句怎么写,才能知道这个人属于那个 中心
查出的结果是
user dept_parent
张三 it中心
李四 行政中心
小王 研发中心

...全文
268 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangdehao 2007-05-18
  • 打赏
  • 举报
回复
晕,搞错了,原来是棵树 -_-###
bill024 2007-05-18
  • 打赏
  • 举报
回复
create function f_getParent(@child varchar(20))
returns varchar(30)
as
begin
while exists(select 1 from t2 where dept_name=@child and dept_parent<>'')
select @child=dept_parent from t2 where dept_name=@child
return @child
end
go

create table t1([user] varchar(20),dept varchar(20))
insert t1 select '张三','it部'
union all select '李四','人事科'
union all select '小王','第一产品科'

create table t2(dept_name varchar(30),dept_parent varchar(30))
insert t2 select 'it部','it中心'
union all select '人事科','行政部'
union all select '行政部','行政中心'
union all select '第一产品科','第一产品软件部'
union all select '第一产品软件部','第一产品部'
union all select '第一产品部','研发中心'

select [user],dept_parent=dbo.f_getParent(dept) from t1

drop table t1,t2
drop function f_getParent

user dept_parent
-------------------- ------------------------------
张三 it中心
李四 行政中心
小王 研发中心

(所影响的行数为 3 行)
gahade 2007-05-18
  • 打赏
  • 举报
回复
楼上的忽视了部门的父子结构.
shuai45 2007-05-18
  • 打赏
  • 举报
回复
select t1.user,t1.dept,t2.dept_parent
from 表1 t1 inner join 表2 t2
on t1.dept=t2.dept_name
gahade 2007-05-18
  • 打赏
  • 举报
回复
drop table 表1,表2
go
create table 表1([user] varchar(10),dept varchar(20))
insert into 表1
select '张三','it部'
union all select '李四','人事科'
union all select '小王','第一产品科'

create table 表2(dept_name varchar(20),dept_parent varchar(20))
insert into 表2
select 'it部','it中心'
union all select '人事科','行政部'
union all select '行政部','行政中心'
union all select '第一产品科','第一产品软件部'
union all select '第一产品软件部','第一产品部'
union all select '第一产品部','研发中心'
go
create function f_getparent(@dept_name varchar(20))
returns varchar(20)
as
begin
declare @dept_parent varchar(100)
select @dept_parent=dept_parent from 表2 where dept_name=@dept_name
while exists(select 1 from 表2 where dept_name=@dept_parent)
begin
select @dept_parent=dept_parent from 表2 where dept_name=@dept_parent
end
return @dept_parent
end
go
select [user],dbo.f_getparent(dept) as dept_parent from 表1
/*
user dept_parent
---------- --------------------
张三 it中心
李四 行政中心
小王 研发中心

(所影响的行数为 3 行)
*/
ziyulin0311 2007-05-18
  • 打赏
  • 举报
回复
up
wangdehao 2007-05-18
  • 打赏
  • 举报
回复
select a.user,a.dept,b.dept_parent
from tb1 a left join tb2 b
on a.dept=b.dept_name
ziyulin0311 2007-05-18
  • 打赏
  • 举报
回复
up

34,588

社区成员

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

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