Skip to content
Advertisement

How to use expression as LAG() second parameter on MySQL 8 (like MSSQL)?

I am trying to migrate this SQL SERVER query:

dbfiddle link

To MySQL 8 (same query):

dbfiddle link

Unfortunately I got this error:

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

Is it possible to “port” this query to mysql?

Thanks in advance !

Advertisement

Answer

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.

In MySQL 8 you would need to make a dynamic SQL query out of it, as offset param of LAG() does not support SQL expressions..

Note: FLOOR() is there to fix 19874.00 not giving a error on the lag function. Offcource you could rewite that SET @sql := CONCAT("..") part different, just use the writing style you understand the best.

Result

see demo

This works because PREPARE q FROM @sql; generates this SQL. (Vignesh Kumar A answer)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement