我尝试了以下查询:
studentcal3 <- function(x,y)
{
i<- x
print(i)
j <- y
print(j)
demo1 <-sqldf("SELECT a.StudentName, (b.marks/a.marks) as difference from
(select Date, StudentName, marks from studenthistorydemo WHERE Date= i) as a
INNER JOIN (select Date, StudentName, marks from studenthistorydemo where
Date= j) as b on a.marks= i and b.marks= j WHERE a.marks = i and b.marks =
j and a.StudentName=b.StudentName")
}
然后调用函数
studentcal3('2014-01-01','2014-01-02')
错误: - rsqlite_send_query中的错误(conn @ptr,statement):没有这样的列:i
如何解决这个问题? P.S - 我是R的新手
答案 0 :(得分:0)
引擎应该如何知道,哪些部分是外部变量?您必须使用字符串连接(Read about paste()
)。请注意,您必须在单引号内以及与文化和语言无关的格式传递变量!
studentcal3 <- function(x,y)
{
i<- x
print(i)
j <- y
print(j)
cmd <-paste("SELECT a.StudentName, (b.marks/a.marks) as difference from ",
"(select Date, StudentName, marks from studenthistorydemo WHERE Date='",i,"') as a ",
"INNER JOIN (select Date, StudentName, marks from studenthistorydemo where ",
"Date='",j,"') as b on a.marks='",i,"' and b.marks='",j,
"' WHERE a.marks ='",i,"' and b.marks ='",j,"' and a.StudentName=b.StudentName",sep="")
#demo1 <-sqldf(cmd)
print(cmd)
}
studentcal3('2014-01-01','2014-01-02')
结果
“选择a.StudentName,(b.marks / a.marks)作为区别(选择 日期,学生姓名,来自studenthistorydemo的标记 Date ='2014-01-01')作为内部联接(选择日期,学生名称,标记 来自studenthistorydemo,其中Date ='2014-01-02')为b on a.marks ='2014-01-01'和b.marks ='2014-01-02'WHERE a.marks ='2014-01-01'和b.marks ='2014-01-02'和a.StudentName = b.StudentName“
注意sql注入!您可以构建具有真实参数的语句,以避免注入攻击。
如果这个陈述真的能提供你期望的另一个问题。您可以打印出来并将其粘贴到查询窗口中以便先测试它......