首页 > 解决方案 > 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 是空数据集。表中无可用数据

谁能帮我理解,为什么数据没有返回?

编辑

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 个观察结果。所以我希望我的查询会返回这个 data.frame

标签: rodbcrodbc

解决方案


我不确定百分位数的东西;我会把它留给你来理顺这部分。无论如何,这是我使用 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/


推荐阅读