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

合并两个表的问题
有以下两个表:
表2:
P241799 GWP0800770 pc. RMB 0.008
201806 GWP0700225 pc. HKD 0.06
PU300412 NULL NULL NULL NULL
表2:
P241799 NULL NULL NULL NULL
201806 NULL NULL NULL NULL
PU300412 ITP1000141 pc. HKD 0.135
要以下結果,如何做到呢?
P241799 GWP0800770 pc. RMB 0.008
201806 GWP0700225 pc. HKD 0.06
PU300412 ITP1000141 pc, HKD 0.135

排序不得调整,只能按这个顺序。

------解决方案--------------------
SQL code

declare @表1 table (c1 varchar(8),c2 varchar(10),c3 varchar(3),c4 varchar(3),c5 numeric(4,3))
insert into @表1
select 'P241799','GWP0800770','pc.','RMB',0.008 union all
select '201806','GWP0700225','pc.','HKD',0.06 union all
select 'PU300412',null,null,null,null

declare @表2 table (c1 varchar(8),c2 varchar(10),c3 varchar(3),c4 varchar(3),c5 numeric(4,3))
insert into @表2
select 'P241799',null,null,null,null union all
select '201806',null,null,null,null union all
select 'PU300412','ITP1000141','pc.','HKD',0.135

select 
ISNULL(a.c1,b.c1) AS c1,
ISNULL(a.c2,b.c2) AS c2,
ISNULL(a.c3,b.c3) AS c3,
ISNULL(a.c4,b.c4) AS c4,
ISNULL(a.c5,b.c5) AS c5
from @表1 a
LEFT JOIN @表2 b ON a.c1=b.c1

/*
c1       c2         c3   c4   c5
-------- ---------- ---- ---- ---------------------------------------
P241799  GWP0800770 pc.  RMB  0.008
201806   GWP0700225 pc.  HKD  0.060
PU300412 ITP1000141 pc.  HKD  0.135
*/