我有两个表是这样的
表一:
ID pid VALUE
1 2 a
2 2 b
3 4 a
4 4 b
表二:
PID NAME
2 FIRST
4 SECOND
表一表二间通过PID相关联
我想通过查询返回的结果集是这样的:
ID NAME VALUE
1 FIRST a,b
2 SECOND a,b
请问这个查询怎么写啊,感激不尽
...全文
641打赏收藏
一个问题求解
我有两个表是这样的 表一: ID pid VALUE 1 2 a 2 2 b 3 4 a 4 4 b 表二: PID NAME 2 FIRST 4 SECOND 表一表二间通过PID相关联 我想通过查询返回的结果集是这样的: ID NAME VALUE 1 FIRST a,b 2 SECOND a,b 请问这个查询怎么写啊,感激不尽
--创建策划试环境
create table A(ID int,pid int,value varchar(10))
create table B(pid int,name varchar(10))
insert A
select 1,2,'a' union
select 2,2,'b' union
select 3,4,'a' union
select 4,4,'b'
insert B select 2,'FIRST' union select 4,'SECOND'
go
if exists(select 1 from sysobjects where id=object_id('dbo.getstr') and xtype='FN')
drop function dbo.getstr
go
create function getstr
(
@pid int
)
returns varchar(20)
as
begin
declare @str varchar(20)
set @str=''
select @str=@str+','+value from A where pid=@pid
return stuff(@str,1,1,'')
end
go
--测试
declare @tb table(ID int identity,Name varchar(20),value varchar(20))
insert @tb(name,value)
select distinct B.Name,[VALUE]=dbo.getstr(A.pid) from A join B on A.pid=B.pid
select * from @tb
--删除测试环境
drop table A,B
--结果
/*
ID Name value
----------- -------------------- --------------------
1 FIRST a,b
2 SECOND a,b