gpt4 book ai didi

mysql - 如何在 MySQL 8(如 MSSQL)上使用表达式作为 LAG() 第二个参数?

转载 作者:行者123 更新时间:2023-11-29 05:47:16 25 4
gpt4 key购买 nike

我正在尝试迁移此 SQL SERVER 查询:

SELECT year, sales,   
LAG(year-2, 2*(SELECT MIN(sales) FROM product_sales), sales/2.0 ) OVER (ORDER BY year) AS no_sense
FROM product_sales;

dbfiddle link

MySQL 8(相同的查询):

dbfiddle link

不幸的是我得到了这个错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*(SELECT MIN(sales) FROM product_sales), sales/2.0 ) OVER (ORDER BY year) AS no_' at line 2

是否可以将此查询“移植”到 mysql?

提前致谢!

最佳答案

Note: this answer is based on the Vignesh Kumar A 's answer. So why MySQL 8 does not support that SQL Server syntax is already fully explained in his answer, i choose to not explain it double.

在 MySQL 8 中,您需要从中进行动态 SQL 查询,因为 LAG() 的偏移参数不支持 SQL 表达式。

SET @sql = CONCAT("
SELECT
year
, sales
, LAG(year-2, ",(SELECT FLOOR(MIN(sales)) FROM product_sales),", sales/2.0 ) OVER (ORDER BY year) AS no_sense
FROM product_sales;
");

PREPARE q FROM @sql;
EXECUTE q;

注意 FLOOR() 是为了修复 19874.00 而不是在滞后函数上给出错误。在场外,您可以重写 SET @sql := CONCAT("..") 部分 different ,只需使用您最了解的写作风格即可。

结果

| year | sales | no_sense |
| ---- | ----- | -------- |
| 2017 | 55000 | 27500 |
| 2017 | 78000 | 39000 |
| 2017 | 49000 | 24500 |
| 2017 | 32000 | 16000 |
| 2018 | 41000 | 20500 |
| 2018 | 89651 | 44825.5 |
| 2018 | 19874 | 9937 |
| 2018 | 32562 | 16281 |
| 2019 | 87456 | 43728 |
| 2019 | 75000 | 37500 |
| 2019 | 96500 | 48250 |
| 2019 | 85236 | 42618 |

demo

这是有效的,因为 PREPARE q FROM @sql; 生成了这个 SQL。 (Vignesh Kumar 的回答)

SELECT 
year
, sales
, LAG(year-2, 19874, sales/2.0 ) OVER (ORDER BY year) AS no_sense
FROM product_sales;

关于mysql - 如何在 MySQL 8(如 MSSQL)上使用表达式作为 LAG() 第二个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58733723/

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