我有以下数据框,其中包含AxiomaID。
x<-c(0123, 234, 2348, 345, 3454)
尝试在R中运行以下SQL查询。
SQL6<-data.frame(sqlQuery(myConn, "SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID = x"))
如何将包含AxiomaID的所有x值粘贴到SQL查询中?
答案 0 :(得分:3)
尝试以下查询:
SQL6<-data.frame(sqlQuery(myConn, paste("SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID IN (", paste(x, collapse = ", "), ")")))
希望它有所帮助!
答案 1 :(得分:0)
你会尝试像
这样的功能InsertListInQuery <- function(querySentence, InList) {
InValues <- ""
for (i in 1:length(InList)){
if (i < length(InList)) {
InValues <- paste(InValues,InList[[i]],",")}
else {
InValues <- paste(InValues,InList[[i]],sep = "")
}
}
LocOpenParenthesis <- gregexpr('[(]', querySentence)[[1]][[1]]
LocCloseParenthesis <- gregexpr('[)]', querySentence)[[1]][[1]]
if (LocCloseParenthesis-LocOpenParenthesis==1) {
querySentence<- gsub("[(]", paste("(",InValues,sep = ""), querySentence)
}
return (querySentence )
}
函数InsertListInQuery要求您将原始查询更改为在WHERE clausule中使用约束IN()的查询。函数的作用是使字符串与用逗号分隔的向量元素相符,并替换&#34;(&#34;字符串与组成的字符串。最后,返回一个字符变量。 因此,您可以定义约束元素列表的向量,查询并调用函数,如下所示:
x<-c(0123, 234, 2348, 345, 3454)
query <- "SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID IN ()"
finalQuery <- InsertListInQuery(query, x)
finalQuery的价值是:
finalQuery
[1] "SELECT top 10 [AxiomaDate] \n ,[RiskModelID]\n,[AxiomaID]\n,[Factor1]\nFROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]\nWhere AxiomaID IN ( 123 , 234 , 2348 , 345 ,3454)"
注意带有特殊字符的行返回\ n。
我希望它可以提供帮助。