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

这种合并如何进行?
有两个表:
table   A       ID       VALUE
                      1           a  
                      1           b
                      2           c
table   B     ID           VALUE
                    1             A
                    2             B
                    2             C
根据两个表的id进行合并,需要将它们合并成这种形式:
                  ID           VALUE1         VALUE2
                  1                 a                   A
                  1                 b                   NULL
                  2                 c                   B
                  2                 NULL             c  


------解决方案--------------------
declare @A table (ID int, Value varchar(10))
insert @A
select 1, 'a ' union all
select 1, 'b ' union all
select 2, 'c '
declare @B table (ID int, Value varchar(10))
insert @B
select 1, 'A ' union all
select 2, 'B ' union all
select 2, 'C '
select ID = case when a.ID is not null then a.ID else b.ID end, Value1 = a.Value, Value2 = b.Value from @A a full join @B b on a.id = b.id and a.Value = b.Value order by ID

------解决方案--------------------

create table tabA(ID int, Value varchar(10))
insert tabA
select 1, 'a ' union all
select 1, 'b ' union all
select 2, 'c '
create table tabB(ID int, Value varchar(10))
insert tabB
select 1, 'A ' union all
select 2, 'B ' union all
select 2, 'C '

select id=isnull(a.id,b.id),
c1=case when (select 1 from (select id,cc=min(value) from tabb group by id) t where t.id=id and t.cc=b.value)=1 then a.value else null end,
c2=case when (select 1 from (select id,cc=min(value) from taba group by id) t where t.id=id and t.cc=a.value)=1 then b.value else null end
from tabA a full join tabB b on a.id = b.id order by ID

drop table tabA,tabB

/*

id c1 c2
----------- ---------- ----------
1 a A
1 b NULL
2 c B
2 NULL C

(4 row(s) affected)
*/

------解决方案--------------------
create table t1(ID int, Value varchar(10))