当前位置: 代码迷 >> Sql Server >> 求教SQL,该如何处理
  详细解决方案

求教SQL,该如何处理

热度:62   发布时间:2016-04-27 17:42:37.0
求教SQL
有表1
a         b
01       a1
02       a2

表2

c         d
01       d1
02       d2
01       d3
02       d4
03       d5


要得到结果:
01,a1,d1、d3

如何写啊?


另:

qq群:19877329

------解决方案--------------------
declare @a varchar(200)
select a,@a=coalesce(@a+ ', ', ' ')+b from (select a,b from tb1 Union All select c,d from tb2) aa where a= '01 '
------解决方案--------------------
先union all 表


declare @str varchar(2000)
set @str= 'c, '
select @[email protected]+d from (a 表union all b表) 表
print @str
------解决方案--------------------
create function udf_getid(@p varchar(10))
returns varchar(8000)
as
begin
declare @p1 varchar(8000)

select @p1=isnull(@p1, ' ')+ d + ', ' from t2 where [email protected]
select @p1=substring(@p1,1,len(@p1)-1)

return @p1
end

create table t1(a varchar(10) null,b varchar(10) null)
create table t2(c varchar(10) null,d varchar(10) null)

insert into t1(a,b) values( '01 ', 'a1 ')

insert into t1(a,b) values( '02 ', 'a2 ')

insert into t2(c,d)
select
'01 ', 'd1 ' union all select
'02 ', 'd2 ' union all select
'01 ', 'd3 ' union all select
'02 ', 'd4 ' union all select
'03 ', 'd5 '

select t1.a,dbo.udf_getid(t1.a) from t1
  相关解决方案