0

I'm trying to get moving average by weekday, for that I'm using sql query. Dataframe is

data

and sqldf code:

ma_782 =  sqldf("SELECT  
         t1.Id_indicator,   t1.Hour,  
 (  
  select SUM(t2.Value) / COUNT(t2.Value)                                 
    FROM  max_value_782 AS t2  
    WHERE   
        t1.Hour = t2.Hour and  
             weekdays.Date(t1.Date) = weekdays.Date(t2.Date)  
            and DATEDIFF(t1.Date, t2.Date) BETWEEN 1 AND 42        
  ) AS 'MA_by_weekday'  
FROM max_value_782 AS t1  ;")  

This gives error

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

while it works from simple select:

sqldf("select * from max_value_782")
0

1 Answer 1

2

Consider replacing the weekdays. method as this syntax assumes a table qualifier. Since by default sqldf uses the SQLite dialect, use strftime to compare weekdays. Also, single quotes are used for string literals and not to enclose table/field identifiers. SQLite can uses brackets, backticks, or double quotes, or none if reserved words/special characters are not used.

ma_782 =  sqldf("SELECT  t1.Id_indicator, t1.Hour,  
                         (SELECT AVG(t2.Value)
                          FROM max_value_782 AS t2  
                          WHERE t1.Hour = t2.Hour 
                          AND strftime('%w', t1.Date) = strftime('%w', t2.Date)  
                          AND (t2.Date - t2.Date) BETWEEN 1 AND 42        
                         ) AS MA_by_weekday  
                FROM max_value_782 AS t1;")  
Sign up to request clarification or add additional context in comments.

2 Comments

Note that the semicolon is not needed.
No problem...Glad to help. Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.