有表1和表2,如何加入它们并创建表3?似乎既没有离开加入也没有联盟都会做到这一点。 谢谢!
表1
Key Var1 Var2
1 A AA
2 B
3 C
4 DD
5 EE
表2
Key Var1 Var2
3 C CC
4 D DD
5 E EE
6 F FF
7 G GG
表3
Key Var1 Var2
1 A AA
2 B
3 C CC
4 D DD
5 E EE
答案 0 :(得分:4)
使用返回第一个非空值的coalesce()
select t1.key,
coalesce(t1.var1, t2.var1) as var1,
coalesce(t1.var2, t2.var2) as var2
from table1 t1
left join table2 t2 on t1.key = t2.key
答案 1 :(得分:1)
以下代码将在SAS中执行,
/* The steps to create table 1 and 2 can be skipped if the Tables exist */
data table1;
infile datalines dsd dlm=' ' missover;
input Key Var1 $ Var2 $;
datalines;
1 A AA
2 B
3 C
4 DD
5 EE
;
run;
data table2;
infile datalines dsd dlm=' ' missover;
input Key Var1 $ Var2 $;
datalines;
3 C CC
4 D DD
5 E EE
6 F FF
7 G GG
;
run;
/* Sort the Dataset T1 and T2 */
proc sort data=table1; by key; run;
proc sort data=table2; by key; run;
/* Final Output */
data want;
merge table1(in=t1) table2(in=t2);
by key;
if t1; /* Keep only the records in Table 1 */
run;
答案 2 :(得分:0)
coalesce是首选方法。长度检查较慢
答案 3 :(得分:0)
我重新创建了你的问题并写了这个查询...
DECLARE @ta table (
id int,
var1 nvarchar(3),
var2 nvarchar(3)
)
DECLARE @tb table(
id int,
var1 nvarchar(3),
var2 nvarchar(3))
INSERT INTO @ta VALUES (1,'A','AA')
INSERT INTO @ta VALUES (2,'B','')
INSERT INTO @ta VALUES (3,'C','')
INSERT INTO @ta VALUES (4,'','DD')
INSERT INTO @ta VALUES (5,'','EE')
INSERT INTO @tb VALUES (3,'C','CC')
INSERT INTO @tb VALUES (4,'D','DD')
INSERT INTO @tb VALUES (5,'E','EE')
INSERT INTO @tb VALUES (6,'F','FF')
INSERT INTO @tb VALUES (7,'G','GG')
SELECT id, var1, var2 from @ta where id <> (
SELECT a.id from @ta AS a INNER JOIN @tb AS b on a.var1 = b.var1)
AND var1 <> ''
UNION
SELECT id, var1, var2 from @tb
我等了,这段代码可以帮到你......