关于 r:如何使用 sqldf 创建嵌套查询

how to create a nested query using sqldf

我正在尝试使用 sqldf 编写嵌套查询。数据集是 \\'contact_fb \\' 。我试图只取行没有 clubmahindra 和列 \\'from_name\\' 中的不同名称,然后左加入 \\'contact_fb \\' 以获取其他列中的所有信息。这不是我想要的结果。

1
contact_fb =structure(list(X = 1:6, from_name = c("Club Mahindra","Club Mahindra","pinto","valencia","valencia","Club Mahindra"), type = structure(c(2L, 2L, 2L, 1L, 1L, 2L), .Label = c("link","photo","status","video"), class ="factor")), .Names = c("X","from_name","type"), row.names = c(NA, 6L), class ="data.frame")

我的尝试是

1
names_cm=sqldf("select t1.from_name, t2.* from (select distinct from_name from  contact_fb where from_name!='Club Mahindra') as t1 left join  ( select * from contact_fb ) as t2 on t1.from_name=t2.t1.from_name")

我终于可以通过

得到它

1
sqldf("select distinct(t1.from_name),t2.* from df t1 left join df t2 on (t1.from_name=t2.from_name) where t1.from_name!='Club Mahindra' group by t1.from_name")

我不明白我哪里出错了。我还能通过我的方式吗?

输出是

1
2
3   Pinto   photo
4   valencia    link


问题末尾显示的输出似乎是一组不同的 from_name, type 对,其中 from_name 不是 "Club Mahindra" 并且我们不需要连接:

1
2
3
sqldf("select distinct from_name, type
       from contact_fb
       where from_name != 'Club Mahindra'")

给予:

1
2
3
  from_name  type
1     pinto photo
2  valencia  link