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 |
- 仔细查看您的查询,您没有从表中选择任何内容。
- 请用文字解释您要做什么并显示预期的输出。
- @谢谢 MIke Fang 我可以让它工作,但它仍然没有给出 reqd 结果。
- @G.Grothendieck 我希望现在会更清楚!
问题末尾显示的输出似乎是一组不同的 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 |
- 我不想这样做,因为我必须写下所有变量的名称,所以我试图加入它以获取不同的值和其余信息。
- select distinct * from … 将对所有变量进行处理。
- 那会给我。会有额外的瓦伦尼卡。 X from_name type 1 3 pinto photo 2 4 valencia link 3 5 valencia link
- 是的,因为 from_name 和 type 的组合没有唯一的 X,所以它给出了每一个。如果您只是想选择一个任意的 X ,那么您可以尝试: sqldf(“select * from contact_fb where from_name != ‘Club Mahindra’ group by from_name, type”) 或者只是 group by from_name ,这取决于您想要什么。
- 是的,这会做。我只是想让事情变得更复杂。谢谢你的帮助。
来源:https://www.codenong.com/36018612/