0

I have a MySQL query which works perfectly but now we are migrating to Postgres and its not working because of the variables used in MySQL. The query is as follows:

SELECT COUNT
    (
        ((
                speed / 3.6 - prevspeed / 3.6 
            ) / TIMESTAMPDIFF ( SECOND, prevdatenew, servertime )) / 9.80665 
    ) AS hardAccels 
FROM
    (
    SELECT ID
        ,
        servertime,
        @prevDateNew AS prevdatenew,
        @prevDateNew := servertime,
        speed,
        @prevSpeed AS prevspeed,
        @prevSpeed := speed 
    FROM
        tc_positions 
    WHERE
        deviceid = 32 
        AND ` ID ` BETWEEN 1318429 
        AND 1322230 
    ) t1 

WHERE
    ((
        speed / 3.6 - prevspeed / 3.6 
    ) / TIMESTAMPDIFF ( SECOND, prevdatenew, servertime )) / 9.80665 > 0.255;

This returns an error because it does not recognize the variables used in mysql:

ERROR:  syntax error at or near ":="
LINE 9:                @prevDateNew:=servertime,
                                   ^

Any ideas to resolve this?

0

1 Answer 1

2

You are using variables for access to values on previous rows. For PostgreSQL you should to use ANSI SQL standard function lag. This function is a window function, so you have to specify order. I have not a your data, your table, so following query is just for inspiration

SELECT speed - lag(speed,1) OVER (ORDER BY id) /
       EXTRACT(epoch FROM (
            servertime - lag(servertime, 1) OVER (ORDER BY id))) 
  FROM tc_positions
   ...

Nice article about this topic is http://www.postgresqltutorial.com/postgresql-window-function/

Sign up to request clarification or add additional context in comments.

Comments

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.