我正在尝试迁移此 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;
至MySQL 8(相同查询):
不幸的是我遇到了这个错误:
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/