Sql 使用Postgres:根据另一个表中的数据创建一列二进制数据

Sql 使用Postgres:根据另一个表中的数据创建一列二进制数据,sql,postgresql,conditional,alter,Sql,Postgresql,Conditional,Alter,我有一个表,其中包含唯一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$I

我有一个表,其中包含唯一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
但它产生了意想不到的结果。它给了我

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”。

case语句解决了您的问题:

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
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;

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;

非常感谢。我以为我已经试过了,但我想我错了,你也对了。这太完美了。我会接受你的回答。只是出于好奇,是什么让它符合ANSI标准?谢谢你!!!!!!!!!!!!!!!!!!!我以为我已经试过了,但我想我错了,你也对了。这太完美了。我会接受你的回答。只是出于好奇是什么让它符合ANSI标准?