R 和 SQL 在查询中引用

R and SQL referencing inside a Query

我已通过 R 连接到 SQL 服务器并具有以下代码。我想在 Factsetdate 的查询之外创建一个引用(请参见下面的粗体)。这意味着从查询中取出 SELECT DATEADD.... 组件并将其添加到一个名为 Date1 的变量中。有没有办法做到这一点?谢谢

SQLCommandEOM<-data.frame(sqlQuery(myConn, 
"SELECT fc.[FactSet Fund Code], fc.FactsetDate, fc.[Asset Class], fc.[Fund Manager],
 d.Id AS DeskID, d.[Name] AS DeskName, fc.[% Factor Risk], fc.[Predicted Tracking Error],
 fc.[Portfolio Predicted Beta]  

 FROM [PortfolioAnalytics].[Data_Factset].[FundChar] fc 
 LEFT OUTER JOIN Data_Axioma.FactSetAccount fsa ON fc.FactsetAccountCode = REPLACE(fsa.Code, '_', '') 
 LEFT OUTER JOIN dbo.Portfolio p ON fsa.PortfolioId = p.Id 
 LEFT OUTER JOIN dbo.Mandate m ON p.UnderlyingId = m.id 
 LEFT OUTER JOIN dbo.Desk d ON m.DeskId = d.Id 
 WHERE IncludesCash = 1 
 AND [FactSet Fund Code] IS NOT NULL 
 AND [Fund Manager] IS NOT NULL 
 AND [Asset Class] IS NOT NULL 
 AND FactsetDate = **(SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)))**
                            ORDER BY [Predicted Tracking Error] DESC"))

这是将 R 对象中的字符串粘贴到 R 中的 SQL 查询的方法:

sql       <- paste("select *
                     from MyDB.dbo.DIM_Person s
                         where OppSFId in ('",
                         paste(sept$OppSFId,collapse = "','"),"')",sep = "")
sept.person <- sqlQuery(db,sql)

我的字符向量称为 sept$OppSFId

因此,如果我正确理解您的示例,您的字符向量将被称为 Date1 并且您想将其替换为:

SQLCommandEOM <- data.frame(sqlQuery(myConn, paste('"SELECT fc.[FactSet Fund Code], fc.FactsetDate, fc.[Asset Class], fc.[Fund Manager],
 d.Id AS DeskID, d.[Name] AS DeskName, fc.[% Factor Risk], fc.[Predicted Tracking Error],
 fc.[Portfolio Predicted Beta]  

 FROM [PortfolioAnalytics].[Data_Factset].[FundChar] fc 
 LEFT OUTER JOIN Data_Axioma.FactSetAccount fsa ON fc.FactsetAccountCode = REPLACE(fsa.Code, '_', '') 
 LEFT OUTER JOIN dbo.Portfolio p ON fsa.PortfolioId = p.Id 
 LEFT OUTER JOIN dbo.Mandate m ON p.UnderlyingId = m.id 
 LEFT OUTER JOIN dbo.Desk d ON m.DeskId = d.Id 
 WHERE IncludesCash = 1 
 AND [FactSet Fund Code] IS NOT NULL 
 AND [Fund Manager] IS NOT NULL 
 AND [Asset Class] IS NOT NULL 
 AND FactsetDate =', Date1,
'ORDER BY [Predicted Tracking Error] DESC"))')