gpt4 book ai didi

mysql - MySQL 中的 Postgres 窗口函数 lag() 等效查询

转载 作者:行者123 更新时间:2023-11-29 02:28:25 24 4
gpt4 key购买 nike

我有 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中转换那个脚本呢?

本题与question的关系如下: reduction of each row in the table of database .

最佳答案

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

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;

关于mysql - MySQL 中的 Postgres 窗口函数 lag() 等效查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17147920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com