Postgres窗口函数lag()在MySQL中等效查询

时间:2013-06-17 12:51:22

标签: mysql postgresql

我有postgresql的脚本如下:

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

但我不使用postgresql,我使用mysql,当我在mysql中尝试该脚本时,该脚本是错误的,那么如何在mysql中转换该脚本?

此问题与问题的关系如下:  reduction of each row in the table of database

2 个答案:

答案 0 :(得分:1)

您需要使用变量来模仿功能。请参阅此页面以获取示例:

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;

答案 1 :(得分:1)

考虑使用现在支持window functions的MYSQL8。