0

我有一个表,其中包含唯一 ID 列表和描述这些 ID 特征的数据列。它采用以下形式:

ID  Tall  Funny  Weight
1   1      0     200
2   0      0     180
3   1      1     250

等等。我有另一个表,它只是具有特征的人的 ID 列表,例如收入超过 10 万。

Rich
1 
3 

我想做的是在第一个表中创建一个列,如果它们在第二个表中,则 = 1,否则为 0。我可以在 R 中这样做:

TableA$Rich <- TableA$ID %in% TableB

但它非常慢,如果没有其他原因,因为我的 postgres (ParAccel/PaDB) 集群的资源比我可以运行 R 的地方多。你能帮我完成这个吗?

我试着做一个左外连接,比如......

create table c as(select a.id, tall, funny, weight,b.id as rich
from tablea a
left outer join tableb b 
on a.id = b.id);

但它产生了意想不到的结果。它给了我

ID  Tall  Funny  Weight  Rich
1   1      0     200     1
2   0      0     180     2
3   1      1     250     3

即使它应该是“1,NULL,3”,我也更喜欢 1 和 0。我担心这可能是数据错误,但数据看起来是正确的。我用 case when 语句尝试了同样的事情,得到了相同的结果,但对于 Rich 的所有值都使用“TRUE”。

4

2 回答 2

2

一个case语句解决了你的问题:

create table c as
    select a.id, tall, funny, weight,
           (case when b.id is null then 0 else 1 end) as rich
    from tablea a left outer join
         tableb b
         on a.id = b.id;
于 2013-08-16T23:24:33.813 回答
1
select
    a.id, tall, funny, weight,
    (b.id is not null)::integer as rich
from
    tablea a
    left outer join
    tableb b on a.id = b.id
于 2013-08-16T23:23:48.077 回答