我有一个表,其中包含唯一 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”。
最佳答案
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;
关于sql - 使用 Postgres : Create a Column of Binary Data Conditional on Data in Another Table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18283438/