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

标签 mysql sql sql-server

我正在尝试迁移此 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/

相关文章:

php - 同时发出 SQL 语句

MySQL查询,如何更好地优化它

c# - Entity Framework - 唯一索引上的 UPSERT

c# - 从数据库中处理 100 万条记录的技术是什么

sql - 简单的 T-SQL 连接问题

mysql - 不小心卸载了mysql服务器

python - 如何使用 executemany 将 Python 中的字典列表插入 MySQL

php - 在 MySql 列中插入多个值

sql - 错误 : ORA-04043: object table name does not exist when describing any table within a specific user workstation from the SQL command line

sql - TSQL - 不使用循环写入 FIZZBUZZ