result_create(conn @ ptr,statement)中的错误:“(”附近:R中的语法错误

时间:2018-10-18 11:29:41

标签: sql r rodbc sqldf

我的帖子与此类似 SQLite in R - error in result_create(conn@ptr, statement) : near ")" 但无法奏效

library("RODBC")
library("sqldf")
library("dplyr")

#connect to sql

dbHandle <- odbcDriverConnect("driver={SQL Server};server=MYNAME;database=AOtest;trusted_connection=true")

sql <- paste0 ("select * from  [AOtest].dbo.basisload1


               order by doc_date") 

ao <- sqlQuery(dbHandle, sql)



sqldf(";With CTE
AS
(
  select *,
  row_number() over (partition by [product_id],shop_code order by [doc_date])-row_number() over (partition by [product_id],shop_code,mark_1 order by [doc_date]) as grp
  from ao
),
CTE1
AS
(
  SELECT *
    FROM CTE c
  OUTER APPLY
  (
    SELECT TOP 1 grp as prvgrp
    FROM CTE
    WHERE mark_1 = 0
    AND doc_date <= c.doc_date
    and [product_id] = c.[product_id]
    and shop_code = c.shop_code
    ORDER BY doc_date DESC
  ) prev
  OUTER APPLY
  (
    SELECT TOP 1 grp as nxtgrp
    FROM CTE
    WHERE mark_1 = 0
    and [product_id] = c.[product_id]
    and shop_code = c.shop_code
    AND doc_date >= c.doc_date
    ORDER BY doc_date 
  ) nxt
)

SELECT c.product_id,c.shop_code,c.doc_date,c.ship_count,c.mark_1,case when med < ship_count then med when ship_count < 0 then 0 else ship_count end as output,
c.ship_count - case when med < ship_count then med when ship_count < 0 then 0 else ship_count end as output1
into test2
FROM CTE1 c
OUTER APPLY (
  SELECT MAX(med) AS med
  FROM
  (
    SELECT PERCENTILE_DISC(0.5) WITHIN GROUP(ORDER BY CASE WHEN ship_count <= 0 THEN 0 ELSE ship_count END) OVER (PARTITION BY [product_id],shop_code,grp) AS med
    FROM CTE
    WHERE grp IN (nxtgrp,prvgrp)
    and [product_id] = c.[product_id]
    and shop_code = c.shop_code
  )r
)c2
order by doc_date")

所以是错误

Error in result_create(conn@ptr, statement) : near "(": syntax error

在我的情况下如何避免此错误。 当然,我可以从SQL Server Management Studio中运行此代码,但是服务器上安装了sql的服务器,一直被其他专家和其他任务忙着,仅在我的服务器上运行。

0 个答案:

没有答案