如何使用sqldf创建嵌套查询

时间:2016-03-15 17:53:15

标签: r sqldf

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

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")

我的尝试是

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")

我终于可以通过

获得它
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")

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

输出

3   Pinto   photo
4   valencia    link

1 个答案:

答案 0 :(得分:0)

问题末尾显示的输出似乎是一组from_nametype对,from_name不是"Club Mahindra",我们不会不需要加入:

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

,并提供:

  from_name  type
1     pinto photo
2  valencia  link