pucca
pucca

Reputation: 35

Postgres window function lag() equivalent query in MySQL

I have postgresql's script as follow as:

select student,
       data, 
       number,
       number - lag(number,1,number) over (partition by student order by id) as output
from the_table
order by student, id

but I'm not use postgresql, I use mysql, when I will try that script in mysql, that script is error, so how to convert that script in mysql?

This question relationship with question as follow as: reduction of each row in the table of database.

Upvotes: 2

Views: 1370

Answers (2)

Felipe Valdes
Felipe Valdes

Reputation: 2217

Consider using MYSQL8, which now supports window functions.

Upvotes: 1

Denis de Bernardy
Denis de Bernardy

Reputation: 78523

You need to use variables to mimic the functionality. See this page for examples:

http://www.onlamp.com/pub/a/mysql/2007/04/12/emulating-analytic-aka-ranking-functions-with-mysql.html?page=2

-- Oracle
select DEPTNO, AVG(HIRE_INTERVAL)
   2  from  (select DEPTNO,
   3               HIREDATE - LAG(HIREDATE, 1)
   4                             over (partition by  DEPTNO
   5                                   order by HIREDATE)  HIRE_INTERVAL
   6         from EMPLOYEES)
   7   group by DEPTNO

-- MySQL
select DEPTNO, avg(HIRE_INTERVAL)
       -> from (select DEPTNO,
       ->              if (@dept = DEPTNO,
       ->                     datediff(HIREDATE, @hd) +  least(0, @hd := HIREDATE),
       ->                     NULL + least(0, @dept :=  DEPTNO) + (@hd := NULL))
       ->                                                      HIRE_INTERVAL
       ->        from EMPLOYEES,
       ->            (select (@dept := 0)) as a
       ->        order by DEPTNO, HIREDATE) as b
       -> group by DEPTNO;

Upvotes: 2

Related Questions