日期:2014-05-17  浏览次数:20353 次

该如何连接才能达到这个效果
A1表      B1表
列1 列2  列1 列2 列3
a   值   a   1   值
b        c   1
c        b   2
我要想这个效果请问该如何写
A1 B1  值
a  1
b  1
c  1
a  2
b  2
c  2
其实意思是,B1.列2把列1分为若干组(代号为123...),现在要每组都分别列出A1表的所有组合,如果b1列3有数据,就显示,没有就现在A1的列2

------解决方案--------------------
create table #ta(col1 varchar(10),col2 varchar(10))
insert into #ta(col1,col2)
select 'a',null
union all select 'b',8
union all select 'c',null

create table #tb(col1 varchar(10),col2 varchar(10),col3 varchar(10))
insert into #tb(col1,col2,col3)
select 'a',1,null
union all select 'b',1,null
union all select 'c',2,20
go

select t1.col1,t1.bcol2 as col2,case when t2.col3 is not null then t2.col3 else t1.col2 end as col3
from 
(
select a.col1,b.col2 as bcol2,a.col2
from #ta a,(select distinct col2 from #tb)b
)t1
left join #tb t2 on t1.col1=t2.col1

drop table #ta,#tb

/*
col1 col2 col3
a 1 NULL
b 1 8
c 1 20
a 2 NULL
b 2 8
c 2 20
*/