日期:2014-05-18  浏览次数:20421 次

急急急急急急急急急急急急急急急急!!!!!查询问题
大家过年好
SQL code

现在我有两个表一个是人员表,一个是项目表
我想将两个字段中的信息进行转换
人员表
id    姓名
1     张三
2     李四
项目表
id  项目名称  人员
1     a       1,2,
2     b        1,
我想要这样的结果

项目名称   人员
a          张三,李四
b          张三
不知道我表述的清楚不清楚,谢谢了



------解决方案--------------------
SQL code
if object_id('[人员表]') is not null drop table [人员表]
go
create table [人员表]([id] int,[姓名] varchar(4))
insert [人员表]
select 1,'张三' union all
select 2,'李四'
go
if object_id('[项目表]') is not null drop table [项目表]
go
create table [项目表]([id] int,[项目名称] varchar(1),[人员] varchar(4))
insert [项目表]
select 1,'a','1,2,' union all
select 2,'b','1,'
go

--sql2005及以上版本
;with t1 as(
select b.项目名称,a.姓名
from 人员表 a
join 项目表 b on charindex(','+ltrim(a.id)+',',','+b.人员)>0
)
select 项目名称,
人员=stuff((select ','+姓名 from t1 where 项目名称=t.项目名称 for xml path('')),1,1,'')
from t1 t
group by 项目名称

/**
项目名称 人员
---- --------------------
a    张三,李四
b    张三

(2 行受影响)
**/

--sql2000用函数
create function f_name(@id varchar(10))
returns varchar(1000)
as
begin
  declare @str varchar(1000)
  set @str=''
  select @str=@str+','+姓名 from 人员表 where charindex(','+ltrim(id)+',',','+@id)>0
  return stuff(@str,1,1,'')
end
go 
select 项目名称,人员=dbo.f_name(人员) from 项目表
/**
项目名称 人员
---- -----------------
a    张三,李四
b    张三

(2 行受影响)
**/

------解决方案--------------------
/*
现在我有两个表一个是人员表,一个是项目表
我想将两个字段中的信息进行转换
人员表
id 姓名
1 张三
2 李四
项目表
id 项目名称 人员
1 a 1,2,
2 b 1,
我想要这样的结果
项目名称 人员
a 张三,李四
b 张三
不知道我表述的清楚不清楚,谢谢了
*/
go
if OBJECT_ID('t1') is not null
drop table t1
go
create table t1(
id varchar(5),
pname varchar(10)
)
go
insert t1
select '1','张三' union all
select '2','李四'
go
if OBJECT_ID('t2') is not null
drop table t2
go
create table t2(
id varchar(5),
iname varchar(5),
pname varchar(100)
)
insert t2
select '1','a','1,2,' union all
select '2','b','1,'

go
if OBJECT_ID('fun_tracy') is not null
drop function fun_tracy
go
create function fun_tracy(@id varchar(10))
returns varchar(100)
as
begin
declare @str varchar(100)
set @str=''
select @str=@str+','+pname from t1 
where charindex(','+ltrim(id)+',',','+@id)>0
return stuff(@str,1,1,'')
end


--调用函数:
select iname as 项目名称,项目人员=dbo.fun_tracy(pname) from t2

/*
你要的结果:
项目名称 项目人员
a 张三,李四
b 张三
*/