RODBC表中无可用数据

时间:2018-06-29 12:11:47

标签: r odbc rodbc

我使用RODBC从sql获取数据

sql <- paste0("
              with cte as (
Select *,datePart(WEEKDAY,Dt) as WeekDay,
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY SaleCount) Over (partition by ItemRelation,
DocumentNum, DocumentYear) as PERCENTILE,
avg(SaleCount) over (Partition by ItemRelation, 
DocumentNum, DocumentYear,datePart(WEEKDAY,Dt), IsPromo) as AVG_WeekDay
From [Action].[dbo].[promo_data_copy])
Update a 
Set SaleCount = cte.AVG_WeekDay
From CTE
join [Action].[dbo].[promo_data_copy] a 
  on a.Dt = cte.dt
 and a.ItemRelation=cte.ItemRelation 
 and a.DocumentNum = cte.DocumentNum 
 and a.DocumentYear = cte.DocumentYear 
 and a.ispromo = cte.ispromo
Where CTE.PERCENTILE < CTE.SaleCount
and datePart(WEEKDAY,CTE.Dt) < 5
and CTE.ispromo = 0 ;")



df <- sqlQuery(dbHandle, sql)
View(df)

和df是空数据集。  表中没有可用数据

anobody可以帮助我理解为什么不返回数据吗?

编辑

Dt  ItemRelation    SaleCount   DocumentNum DocumentYear    IsPromo
2017-10-12 00:00:00.000 13322   7   36  2017    0
2017-10-12 00:00:00.000 13322   35  4   2017    0
2017-10-12 00:00:00.000 158121  340 41  2017    0
2017-10-12 00:00:00.000 158122  260 41  2017    0
2017-10-13 00:00:00.000 13322   3   36  2017    0
2017-10-13 00:00:00.000 13322   31  4   2017    0
2017-10-13 00:00:00.000 158121  420 41  2017    0
2017-10-13 00:00:00.000 158122  380 41  2017    0
2017-10-14 00:00:00.000 11592   45  33  2017    0
2017-10-14 00:00:00.000 13189   135 33  2017    0
2017-10-14 00:00:00.000 13191   852 33  2017    0
2017-10-14 00:00:00.000 13322   1   36  2017    0
2017-10-14 00:00:00.000 13322   34  4   2017    0
2017-10-14 00:00:00.000 158121  360 41  2017    0
2017-10-14 00:00:00.000 158122  140 41  2017    0

这里是表的前15个观察值。因此,我希望查询将向我返回该数据。

1 个答案:

答案 0 :(得分:0)

我不确定百分位数的内容;我将它留给您,以使该部分理顺。无论如何,这是我使用R查询数据库的方式。

library(RODBC)
dbconnection <- odbcDriverConnect("Driver=ODBC Driver 11 for SQL Server;Server=Server_Name; Database=DB_Name;Uid=; Pwd=; trusted_connection=yes")
initdata <- sqlQuery(dbconnection,paste("select * from MyTable;"))
odbcClose(channel)

这里有一些非常有用的资源可供交叉引用。

http://stackoverflow.com/questions/15420999/rodbc-odbcdriverconnect-connection-error

https://andersspur.wordpress.com/2013/11/26/connect-r-to-sql-server-2012-and-14/