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 中转换该脚本?

本题与题的关系如下: 数据库表中每一行的缩减

4

2 回答 2

2

您需要使用变量来模拟功能。有关示例,请参见此页面:

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;
于 2013-06-17T13:23:54.400 回答
1

考虑使用现在支持窗口函数的 MYSQL8 。

于 2018-07-10T16:14:18.163 回答