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

问题描述 投票:2回答:2

我有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

mysql postgresql
2个回答
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
投票

考虑使用MYSQL8,它现在支持window functions

© www.soinside.com 2019 - 2024. All rights reserved.